class OrdersController < ApplicationController
  
  before_filter :user_authorize
  layout "index",:except => [:getMyOrders,:searchOrder,:searchCancelOrders,:noCustomerInfoOrders,:getOrdersBySearch,
    :getCancelOrdersBySearch,:getOutTicketList,:getInsuranceList,:getSendTicketList,:sendTicketWindow,:outTicketByOrder,
    :addMulOrder,:saveMulOrder,:del_ticket,:del_pnr,:getOrdersByCustomerID,:getTicketsByOrderID,:insuranceWindow,
    :clickTicketTypeProcess,:getCashCheckList,:getEditOrderInfoByID,:saveEditOrder,:getEditTicketInfoByID,:saveEditTicket,
    :getPerformance,:saveSendInfo,:getJJList,:affirmJJ,:cancelJJ,:getOrderUpdateHis,:getPnrInfo,:hotelBooking,:addHotelOrder,:addChildTicket,
    :saveModAirline,:getQ,:getOrderInfoByPnr,:saveDrawTicket,:saveTicketNo,:searchWQR,:getWQR,:searchAppOrders,:getAppOrders,
    :changeAppToYDD,:outInsurance,:saveActivity,:printInsuranceWindow,:checkJt,:getTicketsByTicketId,:getDrawTicketsInfo,
    :saPnr,:getPassengerNamesById,:addGroupPassengers,:saveGroupPassenger,:modGroupPassNum]
  
  #我的订单页面
  def myOrder
  end
  
  #查看业绩
  def checkPerformance
    #权限
    if CommonHelper.rightAuthorization(session[:user_rights],params[:controller],params[:action]) == "false"
      redirect_to(:controller => "index", :action => "main") and return
    end 
  end
  
  #查看订单修改日志
  def checkOrderUpdateHis
    #权限
    if CommonHelper.rightAuthorization(session[:user_rights],params[:controller],params[:action]) == "false"
      redirect_to(:controller => "index", :action => "main") and return
    end 
  end
  
  #积分维护
  def checkPoint
    #权限
    if CommonHelper.rightAuthorization(session[:user_rights],params[:controller],params[:action]) == "false"
      redirect_to(:controller => "index", :action => "main") and return
    end 
  end
  
  #我的订单grid
  def getMyOrders
    begin
      user_id = session[:user_id]
      date_type = params[:date_type]
      date = params[:date]
      status = params[:status]
      t_status = params[:t_status]
      
      date_type = "created_at" if date_type==nil
      if date==nil
        date = Time.new.strftime("%Y-%m-%d")
      end
      if date_type == "created_at"
        sql = " created_at like '"+date+"%'"
      else
        sql = " "+date_type+"='"+date+"'"  
      end
      
      num = 0
      result = "successful"
      rootStr = "[]"
      if user_id
        sql << " and (creator_id="+user_id.to_s+" or owner_id="+user_id.to_s+")" 
        if status && status!=""
          sql << " and status='"+status+"'"
        end
        if t_status && t_status!=""
          sql << " and id in(select o.id from orders as o,tickets as t where t.order_id=o.id and t.status='"+t_status+"')"
        end
        #logger.error "sql="+sql
        
        pageBegin = params[:start]
        pageEnd = params[:limit]
        #logger.error pageBegin
        #logger.error pageEnd
        
        sql << " AND is_locked <> 1"
        pageOrders = Order.find(:all,:conditions => ""+sql)
        num = pageOrders.length if pageOrders 
        orders = Order.find(:all,:conditions => sql,:limit =>pageBegin+","+pageEnd)
        
        if orders && orders.length>0
          rootStr = orders.to_json(:include=>[:customer,:creator,:ticket_outer,:printer,:cash_checker,:canceler,:sender,:jj_man,:jj_affirmer])
        end
      end
      jsonstr="{totalProperty:"+num.to_s+",root:"+rootStr+",info:'"+result+"'}"
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      logger.error "orders getMyOrders :: e="+e.message
    end    
  end
  
  #订单查询总页面
  def searchOrderMain
    #权限,上线时需打开
    #if CommonHelper.rightAuthorization(session[:user_rights],params[:controller],params[:action]) == "false"
      #redirect_to(:controller => "index", :action => "main") and return
    #end 
  end
  
  #查找订单tab页面
  def searchOrder
  end
  
  #查找订单
  def getOrdersBySearch
    begin
      order_no = params[:order_no]
      pnr = params[:pnr]
      customerNo = params[:customerNo]
      customer_name = params[:customer_name]
      customer_phone = params[:customer_phone]
      id_card = params[:id_card]
      isMyOrder = params[:isMyOrder]
      fly_date = params[:fly_date]
      fly_date_to = params[:fly_date_to]
      created_at = params[:created_at]
      created_at_to = params[:created_at_to]
      type = params[:type]
      created_date = params[:created_date]
      created_date_to = params[:created_date_to]
      
      if type && type=="noCustomer"
        sql = " (customer_id is null or customer_id=0 or customer_id=1) "
        if created_date && created_date_to
          created_date_to = (created_date_to.to_date+1).to_s
          sql << " and created_at>='"+created_date+"' and created_at<='"+created_date_to+"'"
        end
      else
        sql = " customer_id is not null"
        if pnr && pnr!=""
          sql << " and pnr='"+pnr+"'"
        end
        if session[:user_id]
          if isMyOrder==nil || isMyOrder=="yes"
            sql << " and (creator_id="+session[:user_id].to_s+" or owner_id="+session[:user_id].to_s+")"
          end
        end
        if fly_date && fly_date!=""
          sql << " and fly_date >= '"+fly_date+"'"
        end
        if fly_date_to && fly_date_to!=""
          fly_date_to = (fly_date_to.to_date+1).to_s
          sql << " and fly_date <= '"+fly_date_to+"'"
        end
        if created_at==nil && created_at_to==nil
          today = Time.new.strftime("%Y-%m-%d")
          sql << " and created_at like '%"+today+"%'"
        end
        if created_at && created_at!=""
          sql << " and created_at > '"+created_at+"'"
        end
        if created_at_to && created_at_to!=""
          created_at_to = (created_at_to.to_date+1).to_s
          sql << " and created_at < '"+created_at_to+"'"
        end
        if order_no && order_no!=""
          #根据票号查询
          sql << " and id in (select distinct order_id from tickets where ticket_no='"+order_no+"')"
          #sql << " and order_no like '%"+order_no+"%'"
        end
        customer_sql = ""
        if customerNo && customerNo!=""
          customer_sql << " and customer_no='"+customerNo+"'"
        end
        if customer_name && customer_name!=""
          customer_sql << " and name like '%"+customer_name+"%'"
        end
        if customer_phone && customer_phone!=""
          customer_sql << " and phone='"+customer_phone+"'"
        end
        if id_card && id_card!=""
          customer_sql << " and card='"+id_card+"'"
        end
        if customer_sql!=""
          customer_sql = "select id from customers where is_locked<>1 " + customer_sql
          sql << " and customer_id in("+customer_sql+" )"
        end
      end
      sql << " AND is_locked <> 1"
      logger.error "sql="+sql
      
      rootStr = "[]"
      orders = Order.find(:all,:conditions => sql)
      if orders && orders.length>0
        rootStr = orders.to_json(:include=>[:customer,:creator,:ticket_outer,:printer,:cash_checker,:canceler,:sender,:jj_man,:jj_affirmer])
      end
      jsonstr="{root:"+rootStr+"}"
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      logger.error "orders getOrdersBySearch :: e="+e.message
    end
  end
  
  #查找取消订单tab页面
  def searchCancelOrders
  end
  
  #查找取消订单
  def getCancelOrdersBySearch
    begin
      pnr = params[:pnr]
      isMyOrder = params[:myOrder]
      cancel_date = params[:cancel_date]
      cancel_date_to = params[:cancel_date_to]
      
      sql = " status='"+Constants::ORDER_STATUS_YQX+"'"
      if pnr && pnr!=""
        sql << " and pnr = '"+pnr+"'"
      end
      if session[:user_id]
        if isMyOrder==nil || isMyOrder=="yes"
          sql << " and canceler_id = "+session[:user_id].to_s
        end
      end
      if cancel_date && cancel_date_to
        cancel_date_to = (cancel_date_to.to_date+1).to_s
        sql << " and cancel_date > '"+cancel_date+"' and cancel_date < '"+cancel_date_to+"'"
      end
      sql << " AND is_locked <> 1"
      logger.error "sql="+sql
      
      pageBegin = params[:start]
      pageEnd = params[:limit]
      
      num = 0
      rootStr = "[]"
      pageOrders = Order.find(:all,:conditions => ""+sql)
      num = pageOrders.length if pageOrders 
      orders = Order.find(:all,:conditions => ""+sql,:limit =>pageBegin+","+pageEnd)
      if orders && orders.length>0
        rootStr = orders.to_json(:include=>[:customer,:creator,:ticket_outer,:printer,:cash_checker,:canceler,:sender,:jj_man,:jj_affirmer])
      end
      jsonstr="{totalProperty:"+num.to_s+",root:"+rootStr+"}"
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end    
  end
  
  #未指定客户订单
  def noCustomerInfoOrders
  end
  
  #未确认的订单
  def searchWQR
  end
  
  def getWQR
    begin
      before = params[:before]
      date = params[:date]
      isMy = params[:isMy]
      date = Time.new.strftime("%Y-%m-%d") if date==nil || date==""
      if before && before=="yes"
        sql = " affirm_date<'"+date+"'"
      else
        sql = " affirm_date='"+date+"'"
      end
      sql << " and (status='"+Constants::ORDER_STATUS_YDD+"' or status='"+Constants::ORDER_STATUS_GQD+"')"
      if session[:user_id]
        if isMy==nil || isMy=="yes"
          sql << " and (creator_id="+session[:user_id].to_s+" or owner_id="+session[:user_id].to_s+")"
        end
      end
      sql << " and id in(select distinct order_id from tickets where status='"+Constants::TICKET_STATUS_WQR+"' and is_locked<>1)"
      sql << " AND is_locked <> 1"
      logger.error "sql="+sql
      
      rootStr = "[]"
      orders = Order.find(:all,:conditions => ""+sql)
      if orders && orders.length>0
        rootStr = orders.to_json(:include=>[:customer,:creator,:ticket_outer,:printer,:cash_checker,:canceler,:sender,:jj_man,:jj_affirmer])
      end
      jsonstr="{root:"+rootStr+"}"
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end 
  end
  
  #查看申请单
  def searchAppOrders
  end
  
  def getAppOrders
    begin
      rootStr = "[]"
      orders = Order.find(:all,:conditions => ["status=? and is_locked <> 1",Constants::ORDER_STATUS_SQD])
      if orders && orders.length>0
        rootStr = orders.to_json(:include=>[:customer,:creator,:ticket_outer,:printer,:cash_checker,:canceler,:sender,:jj_man,:jj_affirmer])
      end
      jsonstr="{root:"+rootStr+"}"
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end 
  end
  
  #申请成功后 将申请单转化为预订单
  def changeAppToYDD
    begin
      result = "转化失败"
      id = params[:id]
      order = Order.find_by_id(id) if id
      if order
        order.status = Constants::ORDER_STATUS_YDD
        if order.save
          Ticket.update_all("status='"+Constants::TICKET_STATUS_QRCP+"'",["order_id=?",id])
          result = "转化成功"
        end
      else
        result = "获取订单失败"
      end
      render :text=>result, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end 
  end
  
  #出票
  def outTicketList
    #权限
    if CommonHelper.rightAuthorization(session[:user_rights],params[:controller],params[:action]) == "false"
      redirect_to(:controller => "index", :action => "main") and return
    end 
  end
  
  def getOutTicketList
    begin
      before = params[:before]
      date_type = params[:date_type]
      date = params[:date]
      
      date = Time.new.strftime("%Y-%m-%d") if date==nil
      date_type = "created_at" if date_type==nil
      if date_type == "created_at"
        if before && before=="yes"
          sql = " created_at<'"+date+"'"
        else
          sql = " created_at like '"+date+"%'"
        end
      else
        if before && before=="yes"
          sql = " "+date_type+"<'"+date+"'"
        else
          sql = " "+date_type+"='"+date+"'"
        end
      end
      area = session[:area]
      if area && area!=""
        sql << " and send_address like '%"+area+"%'"
      end
      sql << " and status in('"+Constants::ORDER_STATUS_YDD+"','"+Constants::ORDER_STATUS_GQD+"') and id in(select distinct order_id from tickets where status='"+Constants::TICKET_STATUS_LJCP+"' or status='"+Constants::TICKET_STATUS_QRCP+"')"
      sql << " AND is_locked <> 1"
      logger.error "sql="+sql
      
      result = ""
      rootStr = "[]"
      orders = Order.find(:all,:conditions => sql)
      if orders && orders.length>0
        rootStr = orders.to_json(:include=>[:customer,:creator,:ticket_outer,:printer,:cash_checker,:canceler,:sender,:jj_man,:jj_affirmer])
      end
      jsonstr="{root:"+rootStr+",info:'"+result+"'}"
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  #出保险
  def outInsuranceList
    #权限
    if CommonHelper.rightAuthorization(session[:user_rights],params[:controller],params[:action]) == "false"
      redirect_to(:controller => "index", :action => "main") and return
    end 
  end
  
  #待出保险的订单
  def getInsuranceList
    begin
      date_type = params[:date_type]
      date = params[:date]
      before = params[:before]
      date = Time.new.strftime("%Y-%m-%d") if date==nil
      date_type = "created_at" if date_type==nil
      if date_type == "created_at" || date_type == "ticket_out_date"
        if before && before=="yes"
          sql = " "+date_type+"<'"+date+"'"
        else
          sql = " "+date_type+" like '"+date+"%'"
        end
      else
        if before && before=="yes"
          sql = " "+date_type+"<'"+date+"'"
        else
          sql = " "+date_type+"='"+date+"'"
        end
      end
      sql << " and status='"+Constants::ORDER_STATUS_YCP+"'"
      area = session[:area]
      if area && area!=""
        sql << " and send_address like '%"+area+"%'"
      end
      sql << " and insurance_number>0 and (insurance_outed is null or insurance_outed<>'已出')"
      sql << " AND is_locked <> 1"
      logger.error "sql="+sql
      
      rootStr = "[]"
      orders = Order.find(:all,:conditions => sql)
      if orders && orders.length>0
        rootStr = orders.to_json(:include=>[:customer,:creator,:ticket_outer,:printer,:cash_checker,:canceler,:sender,:jj_man,:jj_affirmer])
      end
      jsonstr="{root:"+rootStr+"}"
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  #出保险 保存出保险人和时间
  def outInsurance
    begin
      #cardNo = params[:card_no]
      #customerName = params[:customer_name]
      #dateBegin = params[:date_begin]
      #dateEnd = params[:date_end]
      #首先连接保险公司,取得保单号.保单号是以后打印的凭证.
      #登录
      #url = "https://epcis-agent.paic.com.cn/j_security_check?j_username=QDHJSWYXGS-00001&j_password=liutao666"
      #登录时必要的一步,不然认为还是登录失败.这个东西的好处是状态由API保持.不然只提交一个.do是没有状态的.
      #url1 = "https://epcis-agent.paic.com.cn/getAgentInfo.do"
      #选择250型的保险类型
      #url2 = "https://epcis-agent.paic.com.cn/agentApply.do?planCode=250"
      #javaUtil = Rjb::import("JavaUtil")
      #对用户名进行从新编码
      #customerName = javaUtil.stringEncoder(customerName,"GBK")
      #默认全是法定
      #beneficiaryName = javaUtil.stringEncoder("法定","GBK")
      #准备得到保单号的ID
      #url3 = "https://epcis-agent.paic.com.cn/printPolicy.do?flag=9&insuranceBeginTime=#{dateBegin}&insuranceEndTime=#{dateEnd}&applyNum=1&beneficiaryName=#{beneficiaryName}&planCode=250&certificateNo=#{cardNo}&certificateType=01&insuredName=#{customerName}&premium=20.0&insuredAmount=400000.0&printDate=&cancelDate=&queryFlag=0&applyRegisterNo="
      #require 'httpclient'
      #epcisCA = "#{Rails.public_path}/epcis_base64.cer"
      #h = HTTPClient.new()
      #h.ssl_config.set_crl(crl_file)
      #h.ssl_config.set_trust_ca(epcisCA)
      #content = h.get_content(url)
      #有了这个值才是正常登录
      #registerNo=""
      #if content.index("epcisLaasBlankFrame") != nil
      #content1 = h.get_content(url1)
      #content2 = h.get_content(url2)
      #content3 = h.get_content(url3)
      #content3 = h.request('POST',"https://epcis-agent.paic.com.cn", {'flag' => '9','planCode'=>'250' ,'insuranceEndTime' => "2008-08-26", 'action' => "/printPolicy",'applyNum'=>'1','beneficiaryName'=>"法定",'ertificateNo'=>"370208000000000002",'insuredName'=>"张百发",'certificateType'=>'01','premium'=>'20.0','&insuredAmount'=>'400000.0','printDate'=>'','cancelDate'=>'','queryFlag'=>'0','applyRegisterNo'=>''})
      #content3 = h.post(URI.parse(url3))
      #posi =  content3.content.index("id=\"applyRegisterNo\" value=\"")
      #保单号
      #if posi != nil
      #registerNo = content3.content[posi+28,16]
      #end
      #存在保单号的情况下
      #if registerNo != ""
      id = params[:id]
      ticket = Ticket.find_by_id(id) if id
      if ticket
        ticket.insurance_outer_id = session[:user_id]
        ticket.insurance_out_date = Time.new
        ticket.insurance_company = "平安"
        #ticket.insurance_no = registerNo
        ticket.insurance_type = '250'
        
        if ticket.save
          #如果没有其他未出保险的票记录 则将订单的保险记录设置为已出保险
          restT = Ticket.find(:first,:conditions=>["order_id=? and is_locked<>1 and insurance_number>0 and insurance_out_date is null",ticket.order_id])
          if restT==nil
            order = ticket.order
            order.insurance_outed = "已出"
            order.save
          end
          info = "保险支付成功!"
        else
          info = "保存保单时失败"
        end
      else
        info = "获取机票信息失败,当前机票已不存在或直接联系管理员"
      end
      #else
      #  info = "在获取保单号时失败,请联系管理员,或重试一次."
      #end
      #else
      #  info = "在提交保单时,登录失败,请检查Internet联接或联系管理员."
      #end
      result = "{success:true,info:'#{info}'}"
      puts result
      render :text=>result, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  #打印送票单
  def printSendTicketList
    #权限
    if CommonHelper.rightAuthorization(session[:user_rights],params[:controller],params[:action]) == "false"
      redirect_to(:controller => "index", :action => "main") and return
    end 
  end
  
  def getSendTicketList
    begin
      order_no = params[:order_no]
      pnr = params[:pnr]
      link_tel = params[:link_tel]
      link_man = params[:link_man]
      send_address = params[:send_address]
      ticket_out_date = params[:ticket_out_date]
      printed = params[:printed]
      
      ticket_out_date = Time.new.strftime("%Y-%m-%d") if ticket_out_date==nil
      sql = " status='"+Constants::ORDER_STATUS_YCP+"'"
      sql << " and ticket_out_date like '"+ticket_out_date+"%'"
      if order_no && order_no!=""
        sql << " and order_no like '%"+order_no+"%'"
      end
      if pnr && pnr!=""
        sql << " and pnr='"+pnr+"'"
      end
      if link_man && link_man!=""
        sql << " and link_man like '%"+link_man+"%'"
      end
      if link_tel && link_tel!=""
        sql << " and link_tel='"+link_tel+"'"
      end
      if send_address && send_address!=""
        sql << " and send_address like '%"+send_address+"%'"
      end
      if printed && printed=="已打印"
        sql << " and send_printed is not null and send_printed='已打印'"
      elsif printed && printed=="未打印"
        sql << " and (send_printed is null or send_printed<>'已打印')"
      end
      area = session[:area]
      if area && area!=""
        sql << " and send_address like '%"+area+"%'"
      end
      sql << " AND is_locked <> 1"
      logger.error "sql="+sql
      
      result = ""
      rootStr = "[]"
      orders = Order.find(:all,:conditions => sql)
      if orders && orders.length>0
        rootStr = orders.to_json(:include=>[:customer,:creator,:ticket_outer,:printer,:cash_checker,:canceler,:sender,:jj_man,:jj_affirmer])
      end
      jsonstr="{root:"+rootStr+",info:'"+result+"'}"
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  def getSendTicketInfo
    begin
      rootStr = ""
      id = params[:id]
      order = Order.find_by_id(id) if id
      if order
        rootStr = order.to_json(:include=>[:customer,:creator,:ticket_outer,:printer,:cash_checker,:canceler,:sender,:jj_man,:jj_affirmer])
      end
      jsonstr="{root:["+rootStr+"]}"
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  #保存派单信息
  def saveSendInfo
    begin
      
      orderids = params[:orderids]
      sender = params[:sender]
      send_printed = params[:send_printed]
      link_man = params[:link_man]
      link_tel = params[:link_tel]
      send_address = params[:send_address]
      send_date = params[:send_date]
      send_time = params[:send_time]
      send_request = params[:send_request]
      
      result = "{success:false,info:'派单失败'}"
      sql = "send_printed='"+send_printed+"',link_man='"+link_man+"',link_tel='"+link_tel+"',send_address='"+send_address+"',send_time='"+send_time+"',send_request='"+send_request+"'"
      if send_date && send_date!=""
        sql << ",send_date='"+send_date+"'"
      end
      if sender.to_i>0
        sql << ",sender_id="+sender
      end
      sql << ",printer_id="+session[:user_id].to_s if session[:user_id]
      logger.error "saveSendInfo sql="+sql
      
      key = Order.update_all(sql, "id in("+orderids+")")
      logger.error "key="+key.to_s
      if key && key.to_i>0
        result = "{success:true,info:'派单成功'}"
      end
      render :text=>result, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  #送票单打印页面
  def sendTicketWindow
    begin
      tickets = Array.new
      orderids = params[:orderids]
      idArr = orderids.split(",")
      @order = Order.find_by_id(idArr[0])
      for id in idArr
        tickets += Ticket.find(:all,:conditions=>["order_id=?",id])
      end
      @tickets = tickets
      @created_at = ""
      @ticket_out_date = ""
      @created_at = @order.created_at.strftime("%Y/%m/%d %H:%M:%S") if @order.created_at
      @ticket_out_date = @order.ticket_out_date.strftime("%Y/%m/%d %H:%M:%S") if @order.ticket_out_date
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  #查看业绩
  def getPerformance
    begin
      rootStr = ""
      sql = " is_locked <> 1 AND employee_no is not null "
      #sql << " and (user_type is null or user_type='话务员')"
      users = User.find(:all,:conditions=>sql,:order=>"id")
      if users
        from_date = params[:from_date]
        to_date = params[:to_date]
        
        tail_sql = ""
        if from_date && to_date
          to_date = (to_date.to_date+1).to_s
          tail_sql = " updated_at>='"+from_date+"' and updated_at<='"+to_date+"' and "
        end
        
        logger.error from_date
        logger.error to_date
        logger.error tail_sql
        
        for user in users
          no = user.employee_no
          name = user.user_name
          
          sql = "select count(*) as sum from orders where "+tail_sql+" owner_id="+user.id.to_s
          order_sum = Order.find_by_sql(sql)[0].sum
          sql = "select count(*) as sum from orders where "+tail_sql+" owner_id="+user.id.to_s+" and ticket_out_date is not null"
          out_order_sum = Order.find_by_sql(sql)[0].sum
          sql = "select count(*) as sum from tickets where "+tail_sql+" order_id in(select id from orders where owner_id="+user.id.to_s+") and status='"+Constants::TICKET_STATUS_YCP+"'"
          out_ticket_sum = Ticket.find_by_sql(sql)[0].sum
          sql = "select count(*) as sum from orders where "+tail_sql+" owner_id="+user.id.to_s+" and status='"+Constants::TICKET_STATUS_YQX+"'"
          cancel_sum = Order.find_by_sql(sql)[0].sum
          sql = "select sum(insurance_number) as summ from orders where "+tail_sql+" owner_id="+user.id.to_s
          insurance_sum = Order.find_by_sql(sql)[0].summ
          insurance_sum = 0 if insurance_sum==nil
          sql = "select count(*) as sum from orders where "+tail_sql+" owner_id="+user.id.to_s+" and status='"+Constants::ORDER_STATUS_YTD+"'"
          refund_sum = Order.find_by_sql(sql)[0].sum
          sql = "select count(*) as sum from orders where "+tail_sql+" owner_id="+user.id.to_s+" and status='"+Constants::ORDER_STATUS_YZF+"'"
          del_sum = Order.find_by_sql(sql)[0].sum
          
          logger.error "========="
          logger.error no
          logger.error name
          logger.error order_sum
          logger.error out_order_sum
          logger.error out_ticket_sum
          logger.error cancel_sum
          logger.error insurance_sum
          logger.error refund_sum
          logger.error del_sum
          
          rootStr << "," if rootStr!=""
          rootStr << "{'no':'"+no.to_s+"','name':'"+name+"','order_sum':'"+order_sum.to_s+"','out_order_sum':'"+out_order_sum.to_s+"','out_ticket_sum':'"+out_ticket_sum.to_s+"','cancel_sum':'"+cancel_sum.to_s+"','insurance_sum':'"+insurance_sum.to_s+"','refund_sum':'"+refund_sum.to_s+"','del_sum':'"+del_sum.to_s+"'}"
          
        end
      end
      logger.error rootStr
      jsonstr="{root:["+rootStr+"]}"
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  #现金收款
  def cashCheckList
    #权限
    if CommonHelper.rightAuthorization(session[:user_rights],params[:controller],params[:action]) == "false"
      redirect_to(:controller => "index", :action => "main") and return
    end 
  end
  
  def getCashCheckList
    begin
      order_no = params[:order_no]
      pnr = params[:pnr]
      link_tel = params[:link_tel]
      link_man = params[:link_man]
      status = params[:status]
      order_date = params[:order_date]
      
      if status && status!="" && status!="未付款"
        sql = " status='"+status+"'"
      else
        sql = " status='"+Constants::ORDER_STATUS_YCP+"'"
      end
      today = Time.new.strftime("%Y-%m-%d")
      if order_date && order_date=="before"
        sql << " and created_at < '"+today+"'"
      else
        sql << " and created_at like '"+today+"%'"
      end
      if order_no && order_no!=""
        sql << " and order_no like '%"+order_no+"%'"
      end
      if pnr && pnr!=""
        sql << " and pnr='"+pnr+"'"
      end
      if link_man && link_man!=""
        sql << " and link_man like '%"+link_man+"%'"
      end
      if link_tel && link_tel!=""
        sql << " and link_tel='"+link_tel+"'"
      end
      area = session[:area]
      if area && area!=""
        sql << " and send_address like '%"+area+"%'"
      end
      sql << " AND is_locked <> 1"
      logger.error "getCashCheckList sql="+sql
      
      result = ""
      rootStr = "[]"
      orders = Order.find(:all,:conditions => sql)
      if orders && orders.length>0
        rootStr = orders.to_json(:include=>[:customer,:creator,:ticket_outer,:printer,:cash_checker,:canceler,:sender,:jj_man,:jj_affirmer])
      end
      jsonstr="{root:"+rootStr+",info:'"+result+"'}"
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  #保存收款信息
  def saveCashChecker
    begin
      id = params[:id]
      receive = params[:receive]
      pay_type = params[:payType]
      sender = params[:sender]
      remark = params[:remark]
      type = params[:type]
      
      order = Order.find_by_id(id)
      if order
        if pay_type=="积分"
          #如果是积分兑换票 则要扣除积分
          pointHis = PointHis.new
          pointHis.customer_id = order.customer_id
          pointHis.user_id = session[:user_id]
          pointHis.options = "减"
          pointHis.point = receive.to_i
          pointHis.remark = "使用积分付款，订单号是"+order.order_no
          pointHis.save
        end
        if type && type=="zf"
          #作废人、作废时间和作废原因保存在取消相关字段中
          order.status = Constants::ORDER_STATUS_YZF
          order.canceler_id = session[:user_id]
          order.cancel_date = Time.new
          order.cancel_reason = remark
          
          #TODO 处理pnr 直接取消pnr还是需要作废专用命令？
          
        else
          order.status = Constants::ORDER_STATUS_YFK
          order.sender_id = sender.to_i if sender && sender.to_i>0
          order.cash_checker_id = session[:user_id]
          order.cash_get_date = Time.new
          order.remark = remark
        end
        order.receive_cash = receive.to_i
        order.pay_type = pay_type
        if order.save
          if type && type=="zf"
            Ticket.update_all("status='"+Constants::TICKET_STATUS_YZF+"'",["order_id=?",order.id])
          end
          result = "{success:true,info:'保存收款记录成功'}"
        else
          result = "{success:false,info:'保存收款记录失败'}"
        end
      else
        result = "{success:false,info:'获取订单信息失败'}"
      end
      render :text=>result, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  #确认出票,提取订单票号,修改订单状态
  def outTicketByOrder
    begin
      orderid = params[:orderid]
      if params[:handwork]
        tickets = Ticket.find(:all,:conditions=>["order_id=? and ticket_no='' and is_locked<>1",orderid])
        if tickets && tickets.length>0
          result = "请先维护上所有票的票号后再进行【手工出票】操作"
        else
          order = Order.find_by_id(orderid)
          order.ticket_outer_id = session[:user_id]
          order.ticket_out_date = Time.new
          order.status = Constants::ORDER_STATUS_YCP
          if order.save
            Ticket.update_all("status='"+Constants::TICKET_STATUS_YCP+"'",["order_id=?",orderid])
            result = "手工出票成功"
          else
            result = "手工出票失败"
          end
        end
      else
        result = CommonHelper.outTicketByOrder(orderid,session[:user_id],session[:eterm_name],session[:eterm_pswd])
      end
      if result.index("成功")
        order = Order.find_by_id(orderid) if order==nil
        if order
          airStr = " 航班信息:"
          passStr = " 乘客信息:"
          content = " "+order.link_man+"先生/女士 您的编号为"+order.order_no+"的订单已经出票 "
          for ticket in order.tickets
            air_no = ticket.air_no
            if airStr.index(air_no)==nil
              fromto = ticket.fromto
              fromAirportName = Airport.find_by_code(fromto[0,3]).airport_name
              toAirportName = Airport.find_by_code(fromto[3,3]).airport_name
              airStr << " "+air_no+" "+ticket.position+"舱 从"+fromAirportName[fromAirportName.index(" ")+1..-1]+"到"+toAirportName[toAirportName.index(" ")+1..-1]+" "+ticket.fly_date.to_s+" "+ticket.fly_time+"起飞"
            end
            passName = ticket.passenger.name
            if passStr.index(passName)==nil
              passStr << passName+" "
            end
          end
          logger.error passStr
          logger.error airStr
          content << passStr
          content << airStr
          logger.error content
          #发送短消息
#          require "rjb"
#          phone_number = order.link_tel
#          if phone_number.length==11
#            returnedInfos = Rjb::import("JavaSMS").sendSMS(Constants::SMS_URL,Constants::SMS_USER_NAME,Constants::SMS_PASSWORD,phone_number,content,Constants::SMS_HAVEYD)
#            #保存成功的短信息
#            if returnedInfos == "SUCCESS"
#              sms = Sms.new
#              sms.user_id = session[:user_id]
#              sms.content = content
#              sms.phone_number = phone_number
#              sms.save
#            end
#          end
        end
      end
      render :text=>result, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end 
  end
  
  #手工录入票号保存
  def saveTicketNo
    begin
      id = params[:id]
      ticket_no = params[:ticket_no]
      if ticket_no.index("-")==nil
        ticket_no = ticket_no[0,3]+"-"+ticket_no[3..-1]
      end
      result = "{success:false}"
      ticket = Ticket.find_by_id(id)
      if ticket
        #更新该乘客的所有ticket记录的票号
        Ticket.update_all("ticket_no='"+ticket_no+"'",["order_id=? and passenger_id=? and is_locked<>1",ticket.order_id,ticket.passenger_id])
        result = "{success:true,info:'保存成功'}"
      end
      render :text=>result, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end 
  end
  
  def addGroupPassengers
    begin
      @orderid = params[:orderid]
      order = Order.find_by_id(@orderid) if @orderid
      @pass_num = order.seat

    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end 
  end
  
  def saveGroupPassenger
    begin
      result = "{success:false}"
      passStr = params[:passStr]
      orderid = params[:orderid]
      logger.error ">>>>>>>>>>>>>>>>>>>>>>>>>"
      logger.error orderid
      logger.error passStr

      info = CommonHelper.saveGroupPassenger(orderid,passStr,session[:eterm_name],session[:eterm_pswd])

      logger.error info
      result = "{success:true,info:'"+info+"'}"
      render :text=>result, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end 
  end

  def modGroupPassNum
    begin
      logger.error ">>>>>>> modGroupPassNum >>>>>>>>>"
      id = params[:id]
      seat_number = params[:seat_number]
      order = Order.find_by_id(id) if id
      if order && seat_number
        pnr = order.pnr.upcase
        rubySocket = SocketHelper.getSocket(session[:eterm_name],session[:eterm_pswd])
        if rubySocket
          cmd = "rt"+pnr
          logger.error  "-----命令cmd="+cmd
          res = SocketHelper.getCR(rubySocket,cmd,true)
          logger.error  "-----返回结果res="+res
          if res.index("ENTIRELY CANCELLED")
            info = "#{pnr}已经取消"
          elsif res.index(pnr)
            num = order.seat - seat_number.to_i
            cmd = "xeg"+num.to_s
            logger.error  "-----命令cmd="+cmd
            res = SocketHelper.getCR(rubySocket,cmd,true)
            logger.error  "-----返回结果res="+res
            if res.index("0."+seat_number)
              res = SocketHelper.getCR(rubySocket,"@",false)
              logger.error  "-----封口结果res="+res
              if res.index(pnr)
                order.seat = seat_number.to_i
                if order.save
                  info = "修改团体人数成功"
                else
                  info = "修改pnr人数成功,但是保存数据库失败"
                end
              else
                info = "封口失败,返回信息"+res
              end
            else
              info = "修改pnr中人数失败,返回信息"+res
            end
          else
            info = "提取失败,返回信息"+res
          end
          if rubySocket
            rubySocket.close
            rubySocket=nil
          end
        else
          info = "访问放大器失败或当前用户已被占用"
        end
      else
        info = "获取订单失败"
      end
      result = "{success:true,info:'"+info+"'}"
      render :text=>result, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      rubySocket.close if rubySocket
    end 
  end
  
  #多张票的订单页面
  def addMulOrder
    begin
      
      if params[:customerid]
        customerid = params[:customerid]
        @customer = Customer.find_by_id(customerid)
      end
      @customer = Customer.find_by_id(1) if @customer==nil
      
      @airNo = params[:airNo]
      @fromto = params[:fromto]
      @fly_date = params[:fly_date]
      @fly_time = params[:fly_time]
      @arr_time = params[:arr_time]
      @plane_type = params[:plane_type]
      @price = params[:price]
      @position = params[:position]
      
      @trip_type = params[:trip_type]
      @trip_type = "" if @trip_type==nil
      @app_flag = params[:app_flag]
      @group_flag = params[:group_flag]
      
      if @trip_type!=""
        @airNo2 = params[:airNo2]
        @fromto2 = params[:fromto2]
        @fly_date2 = params[:fly_date2]
        @fly_time2 = params[:fly_time2]
        @plane_type2 = params[:plane_type2]
        @price2 = params[:price2]
        @position2 = params[:position2]
        if @trip_type=="wflc"
          @airNo3 = params[:airNo3]
          @airNo4 = params[:airNo4]
          @fromto3 = params[:fromto3]
          @fromto4 = params[:fromto4]
          @fly_date3 = params[:fly_date3]
          @fly_date4 = params[:fly_date4]
          @fly_time3 = params[:fly_time3]
          @fly_time4 = params[:fly_time4]
          @arr_time2 = params[:arr_time2]
          @arr_time3 = params[:arr_time3]
          @arr_time4 = params[:arr_time4]
          @plane_type3 = params[:plane_type3]
          @plane_type4 = params[:plane_type4]
          @price3 = params[:price3]
          @price4 = params[:price4]
          @position3 = params[:position3]
          @position4 = params[:position4]
        end
      end
      
      @from_city = Airport.find_by_code(@fromto[0,3]).airport_name if @fromto[0,3] && Airport.find_by_code(@fromto[0,3])
      @to_city = Airport.find_by_code(@fromto[3..5]).airport_name if @fromto[3..5] && Airport.find_by_code(@fromto[3..5])
      @from_city = @from_city[@from_city.index(" ")+1..-1]
      @to_city = @to_city[@to_city.index(" ")+1..-1]
      @from_city = "" if @from_city == nil
      @to_city = "" if @to_city == nil
      
      if @trip_type && @fromto2
        @from_city2 = Airport.find_by_code(@fromto2[0,3]).airport_name if @fromto2[0,3] && Airport.find_by_code(@fromto2[0,3])
        @to_city2 = Airport.find_by_code(@fromto2[3..5]).airport_name if @fromto2[3..5] && Airport.find_by_code(@fromto2[3..5])
        @from_city2 = @from_city2[@from_city2.index(" ")+1..-1]
        @to_city2 = @to_city2[@to_city2.index(" ")+1..-1]
        if @trip_type=="wflc"
          @from_city3 = Airport.find_by_code(@fromto3[0,3]).airport_name if @fromto3[0,3] && Airport.find_by_code(@fromto3[0,3])
          @to_city3 = Airport.find_by_code(@fromto3[3..5]).airport_name if @fromto3[3..5] && Airport.find_by_code(@fromto3[3..5])
          @from_city3 = @from_city3[@from_city3.index(" ")+1..-1]
          @to_city3 = @to_city3[@to_city3.index(" ")+1..-1]
          
          @from_city4 = Airport.find_by_code(@fromto4[0,3]).airport_name if @fromto4[0,3] && Airport.find_by_code(@fromto4[0,3])
          @to_city4 = Airport.find_by_code(@fromto4[3..5]).airport_name if @fromto4[3..5] && Airport.find_by_code(@fromto4[3..5])
          @from_city4 = @from_city4[@from_city4.index(" ")+1..-1]
          @to_city4 = @to_city4[@to_city4.index(" ")+1..-1]
          
          @from_city3 = "" if @from_city3 == nil
          @to_city3 = "" if @to_city3 == nil
          @from_city4 = "" if @from_city4 == nil
          @to_city4 = "" if @to_city4 == nil
        end
        @from_city2 = "" if @from_city2 == nil
        @to_city2 = "" if @to_city2 == nil
      end
      #logger.error @customer.name
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  #保存多张票的订单
  def saveMulOrder
    begin
      
      #hidden参数
      customerid = params[:customerid]
      airNo = params[:airNo]
      fromto = params[:fromto]
      fly_date = params[:fly_date]
      fly_time = params[:fly_time]
      arr_time = params[:arr_time]
      plane_type = params[:plane_type]
      price = params[:price]
      position = params[:position]
      trip_type = params[:trip_type]
      seat = params[:seat_number]
      group_flag = params[:group_flag]
      
      #航程类型
      if trip_type==nil
        trip_type = ""
      elsif trip_type=="wf"
        trip_type = "往返"
      elsif trip_type=="lc"
        trip_type = "联程"
      elsif trip_type=="wflc"
        trip_type = "联程往返"
      end
      if trip_type!=""
        airNo2 = params[:airNo2]
        fromto2 = params[:fromto2]
        fly_date2 = params[:fly_date2]
        fly_time2 = params[:fly_time2]
        arr_time2 = params[:arr_time2]
        plane_type2 = params[:plane_type2]
        price2 = params[:price2]
        position2 = params[:position2]
        if trip_type=="联程往返"
          airNo3 = params[:airNo3]
          fromto3 = params[:fromto3]
          fly_date3 = params[:fly_date3]
          fly_time3 = params[:fly_time3]
          arr_time3 = params[:arr_time3]
          plane_type3 = params[:plane_type3]
          price3 = params[:price3]
          position3 = params[:position3]
          airNo4 = params[:airNo4]
          fromto4 = params[:fromto4]
          fly_date4 = params[:fly_date4]
          fly_time4 = params[:fly_time4]
          arr_time4 = params[:arr_time4]
          plane_type4 = params[:plane_type4]
          price4 = params[:price4]
          position4 = params[:position4]
        end
      end
      
      #form中的参数
      order_request = params[:order_request]
      status = params[:status]
      fix_type = params[:fix_type]
      tktl_date = params[:tktl_date]
      tktl_time = params[:tktl_time]
      ticket_no = params[:ticket_no]
      owner = params[:owner]
      affirm_date = params[:affirm_date]
      
      link_man = params[:link_man]
      link_tel = params[:link_tel]
      send_address = params[:send_address]
      send_date = params[:send_date]
      send_time = params[:send_time]
      send_request = params[:send_request]
      jj_address = params[:jj_address]
      jj_time = params[:jj_time]
      jj_request = params[:jj_request]
      
      #today = Time.new.strftime("%Y-%m-%d")
      fly_date_cmd = CommonHelper.getCmdDateFormat(fly_date)
      fly_date_cmd2 = CommonHelper.getCmdDateFormat(fly_date2) if fly_date2
      fly_date_cmd3 = CommonHelper.getCmdDateFormat(fly_date3) if fly_date3
      fly_date_cmd4 = CommonHelper.getCmdDateFormat(fly_date4) if fly_date4
      #订单所有人
      uid = session[:user_id]
      if owner.to_i>0
        owner_id = owner.to_i
      else
        owner_id = uid
      end
      
      #出票时限
      fix_type = "HK" if fix_type==nil
      if (fix_type == "HK" || fix_type == "LL") && tktl_date
        tktl_date_cmd = CommonHelper.getCmdDateFormat(tktl_date)
        if tktl_time && tktl_time.index(":")
          tktl_time = tktl_time[0,2]+tktl_time[3,2]
        else
          tktl_time = "1800"
        end
      end
      if status==nil
        if fix_type == "RR"
          status = Constants::TICKET_STATUS_QRCP
        else
          status = Constants::TICKET_STATUS_WQR
        end
      end
      ################### 循环获取乘客姓名 获取拼音并转化编码 ######################
      logger.error "循环获取乘客姓名 获取拼音并转化编码"
      nameString = ""
      cardString = ""
      humanTypeString = ""
      insuranceString = ""
      birthdayString = ""
      nmStr = "nm" #穿入名字命令
      cardStr = "" #穿入证件号命令
      cardStr2 = "" #穿入证件号命令2
      babyStr = "" #婴儿命令
      babyStr2 = "" #婴儿命令2
      
      i_number = 0 #保险总数
      baby_no = 0
      seat_cmd = seat.to_i
      if group_flag && group_flag=="yes"
        #团体票不处理乘客信息
        nameString = "未指定人员"
        humanTypeString = "成人"
        insuranceString = "0"
      else
        for i in 1..seat.to_i
          logger.error "====seat for=="+i.to_s+"===="
          passenger_name = params["pessenger_name_"+i.to_s]
          human_type = params["age_type_"+i.to_s]
          birthday = params["birthday_"+i.to_s]
          birthday = "" if birthday==nil
          id_card = params["card_"+i.to_s]
          id_card = "" if id_card==nil
          insurance_number = params["insurance_"+i.to_s]
        
          logger.error passenger_name
          logger.error human_type
          logger.error birthday
          logger.error id_card
          logger.error insurance_number
        
          i_number += insurance_number.to_i
          nameString << "," if i>1
          nameString << passenger_name
          birthdayString << "," if i>1
          birthdayString << birthday
          cardString << "," if i>1
          cardString << id_card
          humanTypeString << "," if i>1
          humanTypeString << human_type
          insuranceString << "," if i>1
          insuranceString << insurance_number
        
          pass_name = SocketHelper.getTransChineseName(passenger_name)
          if human_type=="婴儿"
            #if birthday.to_date>(today.to_date-365)
            #婴儿
            if passenger_name.index("/")
              name_pinyin = passenger_name
            else
              xing = SocketHelper.getPinYin(passenger_name[0,3])
              ming = SocketHelper.getPinYin(passenger_name[3..-1])
              name_pinyin = xing+"/"+ming
            end
            seat_cmd -= 1 #婴儿不算座位
            baby_no += 1
            baby_date_cmd = CommonHelper.getCmdDateFormat(birthday)
            babyStr << Constants::SEPARATE_KEY
            babyStr << "XN:IN/"+pass_name+"INF("+baby_date_cmd[2,5]+")/P"+baby_no.to_s
            babyStr << Constants::SEPARATE_KEY
            babyStr << "SSR INFT "+airNo[0,2]+" NN1 "+fromto+" "+airNo[2..-1]+" "+position+fly_date_cmd+" "+name_pinyin+" "+baby_date_cmd+"/P"+baby_no.to_s
            if airNo2 && airNo2!=""
              if airNo[0,2]==airNo2[0,2]
                babyStr << Constants::SEPARATE_KEY
                babyStr << "SSR INFT "+airNo2[0,2]+" NN1 "+fromto2+" "+airNo2[2..-1]+" "+position2+fly_date_cmd2+" "+name_pinyin+" "+baby_date_cmd+"/P"+baby_no.to_s
              end
              babyStr2 << Constants::SEPARATE_KEY
              babyStr2 << "XN:IN/"+pass_name+"INF("+baby_date_cmd[2,5]+")/P"+baby_no.to_s
              babyStr2 << Constants::SEPARATE_KEY
              babyStr2 << "SSR INFT "+airNo2[0,2]+" NN1 "+fromto2+" "+airNo2[2..-1]+" "+position2+fly_date_cmd2+" "+name_pinyin+" "+baby_date_cmd+"/P"+baby_no.to_s
            end
            if airNo3 && airNo3!=""
              babyStr << Constants::SEPARATE_KEY
              babyStr << "SSR INFT "+airNo3[0,2]+" NN1 "+fromto3+" "+airNo3[2..-1]+" "+position3+fly_date_cmd3+" "+name_pinyin+" "+baby_date_cmd+"/P"+baby_no.to_s
            end
            if airNo4 && airNo4!=""
              babyStr << Constants::SEPARATE_KEY
              babyStr << "SSR INFT "+airNo4[0,2]+" NN1 "+fromto4+" "+airNo4[2..-1]+" "+position4+fly_date_cmd4+" "+name_pinyin+" "+baby_date_cmd+"/P"+baby_no.to_s
            end
          elsif human_type=="儿童"
            #儿童
            nmStr << "1"+pass_name
            #pass_name << "(UM4)"  #UM指无人陪伴的儿童；4指年龄
            chd_date_cmd = CommonHelper.getCmdDateFormat(birthday)
            nmStr << "CHD("+chd_date_cmd+")"
          else
            if human_type=="教师"
              nmStr << "1"+pass_name+"YDT"
            elsif human_type=="学生"
              nmStr << "1"+pass_name+"YSD"
            else
              nmStr << "1"+pass_name
            end
            if seat.to_i==1
              if id_card && id_card!=""
                cardStr << Constants::SEPARATE_KEY
                cardStr << "SSR FOID "+airNo[0,2]+" HK/NI"+id_card
                if airNo2 && airNo2!=""
                  cardStr2 << Constants::SEPARATE_KEY
                  cardStr2 << "SSR FOID "+airNo2[0,2]+" HK/NI"+id_card
                end
              end
            else
              if id_card && id_card!=""
                card_no = i-baby_no #减去婴儿的数量才是正确的编号
                cardStr << Constants::SEPARATE_KEY
                cardStr << "SSR FOID "+airNo[0,2]+" HK/NI"+id_card+"/P"+card_no.to_s
                if airNo2 && airNo2!=""
                  cardStr2 << Constants::SEPARATE_KEY
                  cardStr2 << "SSR FOID "+airNo2[0,2]+" HK/NI"+id_card+"/P"+card_no.to_s
                end
              end
            end
          end
        end
        logger.error "循环结束,结果如下====="
        logger.error "nmStr="+nmStr
        logger.error "cardStr="+cardStr
        logger.error "cardStr2="+cardStr2
        logger.error "babyStr="+babyStr
        logger.error "babyStr2="+babyStr2
        logger.error nameString
        logger.error humanTypeString
        logger.error cardString
        logger.error birthdayString
        logger.error insuranceString
      end
      
      #定航段的SS命令后面的所有命令
      tail_cmd = ""
      if group_flag && group_flag=="yes"
        tail_cmd << Constants::SEPARATE_KEY
        tail_cmd << "GN:"+seat_cmd.to_s+"ren"
      else
        tail_cmd << Constants::SEPARATE_KEY
        tail_cmd << nmStr
      end
      tail_cmd << Constants::SEPARATE_KEY
      tail_cmd << "ct/81115555-"+session[:employee_no]
      if fix_type=="HK" || fix_type=="LL"
        if tktl_date_cmd && tktl_date_cmd!=""
          tail_cmd << Constants::SEPARATE_KEY
          tail_cmd << "tktl/"+tktl_time+"/"+tktl_date_cmd+"/tao220"
        end
      else
        if ticket_no && ticket_no!=""
          tail_cmd << Constants::SEPARATE_KEY
          tail_cmd << "tkt/"+ticket_no
        end
      end
      tail_cmd2 = ""
      if airNo2 && airNo2!=""
        tail_cmd2 << tail_cmd
        if cardStr2!=""
          tail_cmd2 << cardStr2
        end
        if babyStr2!=""
          tail_cmd2 << babyStr2
        end
        tail_cmd2 << Constants::SEPARATE_KEY
        tail_cmd2 << "@"
      end
      if cardStr!=""
        tail_cmd << cardStr
      end
      if babyStr!=""
        tail_cmd << babyStr
      end
      tail_cmd << Constants::SEPARATE_KEY
      tail_cmd << "@"
      
      result = "订票失败"
      if airNo2 && position2 && fly_date_cmd2 && fromto2
        #往返 联程
        if airNo[0,2]==airNo2[0,2]
          logger.error "-------------往返或者联程是同一家航空公司的航班--------------------"
          #往返或者联程是同一家航空公司的航班
          if fix_type=="HK"
            cmd = "ss"+airNo+position+fly_date_cmd+fromto+seat_cmd.to_s
            cmd << Constants::SEPARATE_KEY
            cmd << "ss"+airNo2+position2+fly_date_cmd2+fromto2+seat_cmd.to_s
            if trip_type=="联程往返"
              cmd << Constants::SEPARATE_KEY
              cmd << "ss"+airNo3+position3+fly_date_cmd3+fromto3+seat_cmd.to_s
              cmd << Constants::SEPARATE_KEY
              cmd << "ss"+airNo4+position4+fly_date_cmd4+fromto4+seat_cmd.to_s
            end
          else
            cmd = "ss"+airNo+position+fly_date_cmd+fromto+fix_type+seat_cmd.to_s
            cmd << Constants::SEPARATE_KEY
            cmd << "ss"+airNo2+position2+fly_date_cmd2+fromto2+fix_type+seat_cmd.to_s
            if trip_type=="联程往返"
              cmd << Constants::SEPARATE_KEY
              cmd << "ss"+airNo3+position3+fly_date_cmd3+fromto3+fix_type+seat_cmd.to_s
              cmd << Constants::SEPARATE_KEY
              cmd << "ss"+airNo4+position4+fly_date_cmd4+fromto4+fix_type+seat_cmd.to_s
            end
          end
          #如果中转是在上海的两个机场之间 则需要转换机场命令
          if fromto[3,3]=="SHA" && fromto2[0,3]=="PVG"
            cmd << Constants::SEPARATE_KEY
            cmd << "sa SHAPVG"
          elsif fromto[3,3]=="PVG" && fromto2[0,3]=="PVG"
            cmd << Constants::SEPARATE_KEY
            cmd << "sa PVGSHA"
          end
          if trip_type=="联程往返"
            if fromto3[3,3]=="SHA" && fromto4[0,3]=="PVG"
              cmd << Constants::SEPARATE_KEY
              cmd << "sa SHAPVG"
            elsif fromto3[3,3]=="PVG" && fromto4[0,3]=="PVG"
              cmd << Constants::SEPARATE_KEY
              cmd << "sa PVGSHA"
            end
          end
          cmd << tail_cmd
          logger.error "----订票命令="+cmd
          rubySocket = SocketHelper.getSocket(session[:eterm_name],session[:eterm_pswd])
          if rubySocket
            res = SocketHelper.getCR(rubySocket,"i",false)
            logger.error "----"+res
            restr = SocketHelper.getCR(rubySocket,cmd,true)
            if rubySocket
              rubySocket.close
              rubySocket=nil
            end
            logger.error "----订票结果="+restr
            if trip_type=="联程往返"
              restr = CommonHelper.getPnrFromSocketResult(restr,airNo,airNo2,airNo3,airNo4)
            else
              restr = CommonHelper.getPnrFromSocketResult(restr,airNo,airNo2,nil,nil)
            end
          else
            restr = ""
          end
          if restr.index(" ") && restr.index(" ")==5
            pnr = restr[0,5]
            if restr.rindex(" ")>=8
              status_type = restr[6,2]
              status_type2 = restr[9,2]
              if trip_type=="联程往返"
                status_type3 = restr[12,2]
                status_type4 = restr[15,2]
              end
            else
              status_type = restr
              status_type2 = fix_type
              if trip_type=="联程往返"
                status_type3 = fix_type
                status_type4 = fix_type
              end
            end
          else
            pnr = ""
            status_type = ""
            status_type2 = ""
            status_type3 = ""
            status_type4 = ""
          end
          logger.error "----提取PNR="+pnr+"----"
          if pnr && pnr.length==5
            #保存订单、票、客户积分返利、送票地址等 设置成一个事务
            if trip_type=="联程往返"
              if CommonHelper.saveMulOrderTicket3(uid,customerid.to_i,owner_id,pnr,link_man,link_tel,send_address,send_date,send_time,send_request,
                  order_request,jj_address,jj_time,jj_request,tktl_date,tktl_time,affirm_date,fix_type,nil,group_flag,
                  nameString,humanTypeString,cardString,birthdayString,insuranceString,status,trip_type,seat,i_number,
                  airNo,fromto,fly_date,fly_time,arr_time,plane_type,position,status_type,price,
                  airNo2,fromto2,fly_date2,fly_time2,arr_time2,plane_type2,position2,status_type2,price2,
                  airNo3,fromto3,fly_date3,fly_time3,arr_time3,plane_type3,position3,status_type3,price3,
                  airNo4,fromto4,fly_date4,fly_time4,arr_time4,plane_type4,position4,status_type4,price4)
                
                result = "订票成功,PNR:#{pnr}"
              end
            else
              if CommonHelper.saveMulOrderTicket2(uid,customerid.to_i,owner_id,pnr,link_man,link_tel,send_address,send_date,send_time,send_request,
                  order_request,jj_address,jj_time,jj_request,tktl_date,tktl_time,affirm_date,fix_type,nil,group_flag,
                  nameString,humanTypeString,cardString,birthdayString,insuranceString,status,trip_type,seat,i_number,
                  airNo,fromto,fly_date,fly_time,arr_time,plane_type,position,status_type,price,
                  airNo2,fromto2,fly_date2,fly_time2,arr_time2,plane_type2,position2,status_type2,price2)
                
                result = "订票成功,PNR:#{pnr}"
              end
            end
            if result.index("订票成功,PNR:")==nil
              result = "PNR已经生成,但是保存订单信息失败,请务必妥善保存PNR:<font color=red>#{pnr}</font>,可利用导入功能将该pnr信息导入系统"
            end
          else
            result = "订票失败,失败原因为:"
            if restr.index("timeout")
              result << "连接服务器超时"
            elsif restr.index("socket is null") || restr==""
              result << "访问服务器失败"
            else
              result << restr
            end
          end
          
        else
          #不是同一家航空公司的航班,只能作为两个订单
          logger.error "-------------不是同一家航空公司的航班,只能作为两个订单-------------"
          if fix_type=="HK"
            cmd = "ss"+airNo+position+fly_date_cmd+fromto+seat_cmd.to_s
          else
            cmd = "ss"+airNo+position+fly_date_cmd+fromto+fix_type+seat_cmd.to_s
          end
          cmd << tail_cmd
          logger.error "----订票命令="+cmd
          rubySocket = SocketHelper.getSocket(session[:eterm_name],session[:eterm_pswd])
          res = SocketHelper.getCR(rubySocket,"i",false)
          logger.error "----"+res
          restr = SocketHelper.getCR(rubySocket,cmd,true)
          if rubySocket
            rubySocket.close
            rubySocket=nil
          end
          logger.error "----订票结果="+restr
          restr = CommonHelper.getPnrFromSocketResult(restr,airNo,nil,nil,nil)
          if restr.index(" ") && restr.index(" ")==5
            pnr = restr[0,5]
            status_type = restr[6,2]
          else
            pnr = ""
            status_type = ""
          end
          logger.error "----获取PNR="+pnr+"----"
          if pnr && pnr.length==5
            #保存订单、票、客户积分返利、送票地址等 设置成一个事务
            if CommonHelper.saveMulOrderTicket(uid,customerid.to_i,owner_id,pnr,link_man,link_tel,send_address,send_date,send_time,send_request,
                order_request,jj_address,jj_time,jj_request,tktl_date,tktl_time,affirm_date,fix_type,nil,group_flag,
                nameString,humanTypeString,cardString,birthdayString,insuranceString,status,trip_type,seat,i_number,
                airNo,fromto,fly_date,fly_time,arr_time,plane_type,position,status_type,price)
              
              result = "订票成功,PNR:#{pnr}"
            else
              result = "第一个航班#{airNo}的PNR已经生成,但是保存订单信息失败,请务必妥善保存PNR:<font color=red>#{pnr}</font>,可利用导入功能将该pnr信息导入系统"
            end
          else
            result = "第一个航班#{airNo}订票失败,失败原因为:"
            if restr.index("timeout")
              result << "连接服务器超时"
            elsif restr.index("socket is null") || restr==""
              result << "访问服务器失败"
            else
              result << restr
            end
          end
          
          if result.index("成功")
            result = "第一个航班#{airNo}订票成功,PNR:#{pnr},订单已保存至系统中<br>"
            logger.error "-------------第二个订单-------------"
            if fix_type=="HK"
              cmd = "ss"+airNo2+position2+fly_date_cmd2+fromto2+seat_cmd.to_s
            else
              cmd = "ss"+airNo2+position2+fly_date_cmd2+fromto2+fix_type+seat_cmd.to_s
            end
            cmd << tail_cmd2
            logger.error "----订票命令="+cmd
            rubySocket = SocketHelper.getSocket(session[:eterm_name],session[:eterm_pswd])
            res = SocketHelper.getCR(rubySocket,"i",false)
            logger.error "----"+res
            restr2 = SocketHelper.getCR(rubySocket,cmd,true)
            if rubySocket
              rubySocket.close
              rubySocket=nil
            end
            logger.error "----订票结果="+restr2
            restr2 = CommonHelper.getPnrFromSocketResult(restr2,airNo2,nil,nil,nil)
            if restr2.index(" ") && restr2.index(" ")==5
              pnr2 = restr2[0,5]
              status_type2 = restr2[6,2]
            else
              pnr2 = ""
              status_type2 = ""
            end
            logger.error "----获取PNR="+pnr2+"----"
            if pnr2 && pnr2.length==5
              #保存订单、票、客户积分返利、送票地址等 设置成一个事务
              if CommonHelper.saveMulOrderTicket(uid,customerid.to_i,owner_id,pnr2,link_man,link_tel,send_address,send_date,send_time,send_request,
                  order_request,jj_address,jj_time,jj_request,tktl_date,tktl_time,affirm_date,fix_type,nil,group_flag,
                  nameString,humanTypeString,cardString,birthdayString,insuranceString,status,trip_type,seat,i_number,
                  airNo2,fromto2,fly_date2,fly_time2,arr_time2,plane_type2,position2,status_type2,price2)
                
                result = "订票成功,由于两个航空公司不同,形成两个订单已保存至系统中,PNR分别是#{pnr} #{pnr2}"
              else
                result << "第二个航班#{airNo2}订票PNR已经生成,但是保存订单信息失败,请务必妥善保存PNR:<font color=red>#{pnr2}</font>,可利用导入功能将该pnr信息导入系统"
              end
            else
              result << "但是第二个航班#{airNo2}订票失败,失败原因为:"
              if restr2.index("timeout")
                result << "连接服务器超时"
              elsif restr2.index("socket is null") || restr2==""
                result << "访问服务器失败"
              else
                result << restr2
              end
            end
          end
        end
      else
        logger.error "-------------单程多人订单-------------"
        if fix_type=="HK"
          cmd = "ss"+airNo+position+fly_date_cmd+fromto+seat_cmd.to_s
        else
          cmd = "ss"+airNo+position+fly_date_cmd+fromto+fix_type+seat_cmd.to_s
        end
        cmd << tail_cmd
        logger.error "----订票命令="+cmd
        rubySocket = SocketHelper.getSocket(session[:eterm_name],session[:eterm_pswd])
        res = SocketHelper.getCR(rubySocket,"i",false)
        logger.error "----"+res
        restr = SocketHelper.getCR(rubySocket,cmd,true)
        if rubySocket
          rubySocket.close
          rubySocket=nil
        end
        logger.error "----订票结果="+restr
        restr = CommonHelper.getPnrFromSocketResult(restr,airNo,nil,nil,nil)
        if restr.index(" ") && restr.index(" ")==5
          pnr = restr[0,5]
          status_type = restr[6,2]
        else
          pnr = ""
          status_type = ""
        end
        logger.error "----获取PNR="+pnr+"----"
        if pnr && pnr.length==5
          #保存订单、票、客户积分返利、送票地址等 设置成一个事务
          if CommonHelper.saveMulOrderTicket(uid,customerid.to_i,owner_id,pnr,link_man,link_tel,send_address,send_date,send_time,send_request,
              order_request,jj_address,jj_time,jj_request,tktl_date,tktl_time,affirm_date,fix_type,nil,group_flag,
              nameString,humanTypeString,cardString,birthdayString,insuranceString,status,trip_type,seat,i_number,
              airNo,fromto,fly_date,fly_time,arr_time,plane_type,position,status_type,price)
            
            result = "订票成功,PNR:#{pnr}"
          else
            result = "PNR已经生成,但是保存订单信息失败,请务必妥善保存PNR:<font color=red>#{pnr}</font>,可利用导入功能将该pnr信息导入系统"
          end
        else
          result = "订票失败,失败原因为:"
          if restr.index("timeout")
            result << "连接服务器超时"
          elsif restr.index("socket is null") || restr==""
            result << "访问服务器失败"
          else
            result << restr
          end
        end
      end
      logger.error "result="+result
      result = "{success:true,info:'"+result+"'}"
      render :text=>result, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      logger.error "order saveMulOrder :: e="+e.message
      #p.close if p
      SocketHelper.closeSocket(rubySocket)
      #ensure
      #  p.close if p  # ... and this always happens.
    end
  end

  #修改航段
  def saveModAirline
    begin
      
      airNo = params[:airNo]
      fromto = params[:fromto]
      fly_date = params[:fly_date]
      fly_time = params[:fly_time]
      arr_time = params[:arr_time]
      plane_type = params[:plane_type]
      price = params[:price]
      position = params[:position]
      
      orderid = params[:orderid]
      option = params[:option]
      option = "mod" if option==nil || option==""
      trip_type = params[:trip_type]
      #航程类型
      if trip_type==nil
        trip_type = ""
      elsif trip_type=="wf"
        trip_type = "往返"
      elsif trip_type=="lc"
        trip_type = "联程"
      elsif trip_type=="wflc"
        trip_type = "联程往返"
      end
      if trip_type!=""
        airNo2 = params[:airNo2]
        fromto2 = params[:fromto2]
        fly_date2 = params[:fly_date2]
        fly_time2 = params[:fly_time2]
        arr_time2 = params[:arr_time2]
        plane_type2 = params[:plane_type2]
        price2 = params[:price2]
        position2 = params[:position2]
        if trip_type=="联程往返"
          airNo3 = params[:airNo3]
          fromto3 = params[:fromto3]
          fly_date3 = params[:fly_date3]
          fly_time3 = params[:fly_time3]
          arr_time3 = params[:arr_time3]
          plane_type3 = params[:plane_type3]
          price3 = params[:price3]
          position3 = params[:position3]
          airNo4 = params[:airNo4]
          fromto4 = params[:fromto4]
          fly_date4 = params[:fly_date4]
          fly_time4 = params[:fly_time4]
          arr_time4 = params[:arr_time4]
          plane_type4 = params[:plane_type4]
          price4 = params[:price4]
          position4 = params[:position4]
        end
      end
      
      result = "操作失败"
      order = Order.find_by_id(orderid)
      if order
        pnr = order.pnr
        rubySocket = SocketHelper.getSocket(session[:eterm_name],session[:eterm_pswd])
        if rubySocket
          server = Constants::SERVER_INFO
          if server.index("pek4.")
            res = SocketHelper.getCR(rubySocket,"i",false)
            res = "OK#"
          else
            #第一次lock
            res = SocketHelper.getCR(rubySocket,"lock",false)
          end
          if res.index("OK#")
            cmd = "rt"+pnr
            logger.error  "-----命令cmd="+cmd
            res = SocketHelper.getCR(rubySocket,cmd,true)
            logger.error  "-----返回结果res="+res
            if res.index("NO PNR")
              result = "该PNR不存在"
            elsif res.index("*THIS PNR WAS ENTIRELY CANCELLED*")
              result = "该PNR已经被取消"
            elsif res==""
              result = "访问放大器失败"
            elsif res.index(pnr)
              res = res.gsub(/\r/,"")
              res = res.gsub(/\n/,"<br>")
              res1 = res.gsub(/ {1,}/," ").strip
              logger.error  "-----整理后结果res1="+res1
              go = true
              seat=0
              if option && option=="mod"
                noStr = ""
                while res1.index(". ")
                  res2 = res1[res1.index(". ")-1..-1]
                  res3 = res2[0,res2.index("<br>")].strip
                  logger.error res3
                  no = res3[0,1]
                  if no.to_i>0
                    if seat==0
                      seat = no.to_i-1
                    else
                      if seat > no.to_i-1
                        seat = no.to_i-1
                      end
                    end
                    noStr << "/" if noStr!=""
                    noStr << no
                  end
                  res1 = res2[res2.index("<br>")+4..-1]
                end
                logger.error "noStr="+noStr
                if noStr!=""
                  cmd = "xe"+noStr
                  logger.error  "-----命令cmd="+cmd
                  res2 = SocketHelper.getCR(rubySocket,cmd,true)
                  logger.error  "-----返回结果res2="+res2
                  if res2.index(pnr)==nil
                    logger.error "-----取消原有航班失败"
                    result = "取消原有航班失败"
                    go = false
                    break
                  elsif res2.index(". ")
                    logger.error "-----还有航班没有被取消失败"
                    result = "还有航班没有被取消失败"
                    go = false
                    break
                  end
                end
              else
                res2 = res1[res1.index(". ")-1..-1]
                res3 = res2[0,res2.index(".")].strip
                seat = res3.to_i-1
              end
              logger.error "座位数="+seat.to_s
              logger.error go
              #TODO 婴儿航段怎么取消？
              if go && seat>0
                date_cmd = CommonHelper.getCmdDateFormat(fly_date)
                date_cmd2 = CommonHelper.getCmdDateFormat(fly_date2) if fly_date2
                date_cmd3 = CommonHelper.getCmdDateFormat(fly_date3) if fly_date3
                date_cmd4 = CommonHelper.getCmdDateFormat(fly_date4) if fly_date4
                if res1.index("TL/")
                  fix_type = ""
                else
                  fix_type = "" #"RR"
                end
                cmd = "ss"+airNo+position+date_cmd+fromto+fix_type+seat.to_s
                if trip_type!=""
                  cmd << Constants::SEPARATE_KEY
                  cmd << "ss"+airNo2+position2+date_cmd2+fromto2+fix_type+seat.to_s
                  if trip_type=="联程往返"
                    cmd << Constants::SEPARATE_KEY
                    cmd << "ss"+airNo3+position3+date_cmd3+fromto3+fix_type+seat.to_s
                    cmd << Constants::SEPARATE_KEY
                    cmd << "ss"+airNo4+position4+date_cmd4+fromto4+fix_type+seat.to_s
                  end
                end
                #如果中转是在上海的两个机场之间 则需要转换机场命令
                if fromto2 && fromto2!=""
                  if fromto[3,3]=="SHA" && fromto2[0,3]=="PVG"
                    cmd << Constants::SEPARATE_KEY
                    cmd << "sa SHAPVG"
                  elsif fromto[3,3]=="PVG" && fromto2[0,3]=="PVG"
                    cmd << Constants::SEPARATE_KEY
                    cmd << "sa PVGSHA"
                  end
                end
                if fromto3 && fromto4
                  if fromto3[3,3]=="SHA" && fromto4[0,3]=="PVG"
                    cmd << Constants::SEPARATE_KEY
                    cmd << "sa SHAPVG"
                  elsif fromto3[3,3]=="PVG" && fromto4[0,3]=="PVG"
                    cmd << Constants::SEPARATE_KEY
                    cmd << "sa PVGSHA"
                  end
                end
                cmd << Constants::SEPARATE_KEY
                cmd << "@"
                
                logger.error  "-----穿入新航段命令cmd="+cmd
                res3 = SocketHelper.getCR(rubySocket,cmd,true)
                logger.error  "-----传入新行段结果res3="+res3
                if res3.index(pnr) && res3.index(airNo)
                  result = "封口成功"
                  if !CommonHelper.modTicketAirline(orderid,trip_type,option,
                      airNo,fromto,fly_date,fly_time,arr_time,position,plane_type,price,
                      airNo2,fromto2,fly_date2,fly_time2,arr_time2,position2,plane_type2,price2,
                      airNo3,fromto3,fly_date3,fly_time3,arr_time3,position3,plane_type3,price3,
                      airNo4,fromto4,fly_date4,fly_time4,arr_time4,position4,plane_type4,price4)
                    if option == "mod"
                      logger.error "-----修改航段成功,但是保存数据库记录失败,pnr是#{pnr}-----"
                      result = "pnr中航班已经修改,但是保存数据库记录失败"
                    else
                      logger.error "-----追加航段成功,但是保存数据库记录失败,pnr是#{pnr}-----"
                      result = "新航班已经追加入PNR,但是保存数据库记录失败"
                    end
                  end
                else
                  result = "穿入新航班失败,返回结果:"+res3
                end
              end 
            else
              logger.error "提取#{pnr}失败,结果是:"+res
              result = "提取#{pnr}失败,返回结果:"+res
            end
          else
            result = "LOCK失败"
          end
          if rubySocket
            rubySocket.close
            rubySocket=nil
          end
        else
          result = "连接放大器失败,或用户"+session[:eterm_name].to_s+"已被占用!"
        end
      else
        result = "获取订单失败,订单编号为#{orderid}"
      end
      logger.error result
      render :text=>result, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      SocketHelper.closeSocket(rubySocket)
    end
  end
  
  #订票--单张票订单
  def command_single(airNo,position,date,fromto,passenger_name,fix_type,human_type,chd_date,id_card,tktl_date,tktl_time,ticket_no)
    begin
      
      #订票命令
      if fix_type.downcase=="hk" || fix_type.downcase=="ll"
        cmd = "ss"+airNo+position+date+fromto+"1"
      else
        cmd = "ss"+airNo+position+date+fromto+fix_type+"1"
      end
      #如果是中文,则获取拼音和ASCII码
      pass_name = SocketHelper.getTransChineseName(passenger_name)
      if human_type.downcase=="chd" && chd_date
        #pass_name << "(UM4)"  #UM指无人陪伴的儿童；4指年龄
        pass_name << "CHD("+chd_date+")"
      elsif human_type.downcase=="baby"
        #xn:in/ 名字 inf(mar99)/p1  #一个成人带一个婴儿（不占座）
      end
      cmd << Constants::SEPARATE_KEY
      cmd << "nm1"+pass_name
      cmd << Constants::SEPARATE_KEY
      cmd << "ct/81115555-"+session[:employee_no]
      if fix_type.downcase=="hk" || fix_type.downcase=="ll"
        if tktl_date && tktl_date!=""
          cmd << Constants::SEPARATE_KEY
          cmd << "tktl/"+tktl_time+"/"+tktl_date+"/tao220"
        end
      else
        if ticket_no && ticket_no!=""
          cmd << Constants::SEPARATE_KEY
          cmd << "tkt/"+ticket_no
        end
      end
      if id_card && id_card!=""
        cmd << Constants::SEPARATE_KEY
        cmd << "SSR FOID "+airNo[0,2]+" HK/NI"+id_card
      end
      cmd << Constants::SEPARATE_KEY
      cmd << "@"
      
      #获取
      logger.error "单人订票命令"
      logger.error cmd
      restr = SocketHelper.callSocket(cmd,session[:eterm_name],session[:eterm_pswd])
      logger.error "单人订票返回结果"
      logger.error restr
      
      return restr
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      logger.error "orders command_single :: e="+e.message
    end
  end
  
  #取消票
  def del_ticket
    begin
      logger.error "====#{params[:controller]} #{params[:action]}===="
      id = params[:id]
      reason = params[:reason]
      reason = "取消" if reason==nil
      ticket = Ticket.find_by_id(id) if id
      if ticket
        restTicket = Ticket.find(:first,:conditions=>["order_id=? and is_locked<>1 and id<>?",ticket.order_id,ticket.id])
        if restTicket
          passenger = ticket.passenger
          if passenger && passenger.name
            pass_name = passenger.name
            pnr = ticket.pnr
            pnr = pnr.upcase #转大写
            #获取取消票的结果
            res = CommonHelper.getCancelTicketResult(pnr,pass_name,session[:eterm_name],session[:eterm_pswd])
            if res.index("成功")
              Ticket.cancelTicketFromOrder(ticket.id,session[:user_id],reason)
              result = "取消票成功"
              #              if Ticket.cancelTicketFromOrder(ticket.id,session[:user_id],reason)
              #                result = "取消票成功"
              #              else
              #                result = "PNR已取消,但删除票记录失败"
              #              end
            else
              result = res
            end
          else
            result = "获取乘客信息失败"
          end
        else
          result = "该订单目前只有一张票,请选择订单右键菜单中的【取消订单】项取消整个订单."
        end
      else
        result = "获取票记录失败"
      end
      if result.index("成功")
        jsonstr="{success:true,info:'"+result+"'}"
      else
        jsonstr="{success:false,info:'"+result+"'}"
      end
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  #取消订单
  def del_pnr
    begin
      logger.error "====del_pnr==="
      id = params[:id]
      reason = params[:reason]
      
      logger.error id
      logger.error reason
      
      reason = "取消" if reason==nil
      order = Order.find_by_id(id) if id
      logger.error order
      if order
        pnr = order.pnr
        logger.error pnr
        #获取取消pnr的结果
        res = CommonHelper.getCancelPnrResult(pnr,session[:eterm_name],session[:eterm_pswd])
        if res.index("成功")
          Ticket.cancelOrderAndTicket(id,session[:user_id],reason)
          result = "取消订单成功"
          #          if Ticket.cancelOrderAndTicket(id,session[:user_id],reason)
          #            result = "取消订单成功"
          #          else
          #            result = "PNR已取消,但删除订单记录失败"
          #          end
        elsif res.index("已经被取消")
          Ticket.cancelOrderAndTicket(id,session[:user_id],reason)
          result = res
        else
          result = res
        end
      else
        result = "获取订单失败"
      end
      logger.error "=== END ==="
      logger.error result
      if result.index("成功")
        jsonstr="{success:true,info:'"+result+"'}"
      else
        jsonstr="{success:false,info:'"+result+"'}"
      end
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  #根据客户得到订单
  def getOrdersByCustomerID
    begin
      #logger.error ">>>> getOrdersByCustomerID >>>>"
      rootStr = "[]"
      id = params[:id]
      if id && id!=""
        sql = "customer_id = "+id
      else
        sql = "(customer_id is null or customer_id=0)"
      end
      sql << " and status not in('"+Constants::ORDER_STATUS_YQX+"','"+Constants::ORDER_STATUS_YZF+"','"+Constants::ORDER_STATUS_YTD+"')"
      sql << " and id in(select order_id from tickets where status = '"+Constants::TICKET_STATUS_WQR+"')"
      sql << " AND is_locked <> 1"
      #logger.error "sql="+sql
      orders = Order.find(:all,:conditions => sql)
      if orders && orders.length>0
        rootStr = orders.to_json(:include=>[:customer,:creator,:ticket_outer,:printer,:cash_checker,:canceler,:sender,:jj_man,:jj_affirmer])
      end
      #logger.error rootStr
      jsonstr="{root:"+rootStr+"}"
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  #根据订单得到票
  def getTicketsByOrderID
    begin
      id = params[:id]
      showCancelTicket = params[:showCancelTicket]
      rootStr = "[]"
      if id && id.to_i>0
        if showCancelTicket && showCancelTicket=="no"
          sql = "order_id="+id+" and status <> '"+Constants::TICKET_STATUS_YQX+"' and status <> '"+Constants::TICKET_STATUS_YTP+"'"
        else
          sql = "order_id="+id
        end
        sql << " AND is_locked <> 1"
        logger.error sql
        tickets = Ticket.find(:all,:conditions => sql)
        if tickets && tickets.length>0
          #rootStr = tickets.to_json(:include=>[:passenger=>[:include=>[:card_type]]])
          #rootStr = tickets.to_json(:include=>{:passenger=>{:include=>:card_type}})
          rootStr = tickets.to_json(:include => [:passenger,:canceler,:insurance_outer])
        end
      end
      jsonstr="{root:"+rootStr+"}"
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  def getTicketsByTicketId
    begin
      rootStr = "[]"
      tid = params[:tid]
      ticket = Ticket.find_by_id(tid) if tid
      if ticket
        sql = " and status <> '"+Constants::TICKET_STATUS_YQX+"' and status <> '"+Constants::TICKET_STATUS_YTP+"' and status <> '"+Constants::TICKET_STATUS_YZF+"'"
        tickets = Ticket.find(:all,:conditions=>["order_id=? and passenger_id=? and is_locked<>1 "+sql,ticket.order_id,ticket.passenger_id])
        
        logger.error tickets.length

        rootStr = tickets.to_json
      end
      jsonstr="{root:"+rootStr+"}"
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  def getDrawTicketsInfo
    begin
      rootStr = "[]"
      tid = params[:tid]
      ticket = Ticket.find_by_id(tid) if tid
      if ticket
        sql = "select sum(price) as d_price,sum(airdrome_tax) as d_tax,sum(fuel_tax) as d_fuel,sum(price_F) as d_f,sum(other) as d_other,sum(total_price) as d_total,sum(insurance_number) as d_insurance from tickets where order_id="+ticket.order_id.to_s
        sql << " and passenger_id="+ticket.passenger_id.to_s+" and status <> '"+Constants::TICKET_STATUS_YQX+"' and status <> '"+Constants::TICKET_STATUS_YTP+"' and status <> '"+Constants::TICKET_STATUS_YZF+"'"
        tickets = Ticket.find_by_sql(sql + " and is_locked<>1 ")
        
        d_price = tickets[0].d_price
        d_tax = tickets[0].d_tax
        d_fuel = tickets[0].d_fuel
        d_f = tickets[0].d_f
        d_other = tickets[0].d_other
        d_total = tickets[0].d_total
        d_insurance = tickets[0].d_insurance
        
        rootStr = "[{'d_name':'"+ticket.passenger.name+"','d_price':'"+d_price.to_s+"','d_tax':'"+d_tax.to_s+"','d_fuel':'"+d_fuel.to_s+"','d_f':'"+d_f.to_s+"','d_other':'"+d_other.to_s+"','d_total':'"+d_total.to_s+"','d_insurance':'"+d_insurance.to_s+"'}]"
      end
      jsonstr="{root:"+rootStr+"}"
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  #出保险页面 需要关联乘客证件号
  def getInsuranceTickets
    begin
      id = params[:id]
      rootStr = "[]"
      if id && id.to_i>0
        sql = "order_id="+id+" and status <> '"+Constants::TICKET_STATUS_YQX+"' and status <> '"+Constants::TICKET_STATUS_YTP+"'"
        sql << " AND is_locked <> 1"
        #logger.error sql
        tickets = Ticket.find(:all,:conditions => sql)
        if tickets && tickets.length>0
          #rootStr = tickets.to_json(:include=>[:passenger=>[:include=>[:card_type]]])
          rootStr = tickets.to_json(:include=>{:passenger=>{:include=>:card_type}})
        end
      end
      jsonstr="{root:"+rootStr+"}"
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  #协助把变量放入网页
  def insuranceWindow
    @passenger_name=params[:passenger_name]
    @card=params[:card]
    @card_type=params[:card_type]
    @fly_date=params[:fly_date]
  end

  #查看经停城市
  def checkJt
    begin
      air_no = params[:air_no]
      date = params[:date]
      rubySocket = SocketHelper.getSocket(session[:eterm_name],session[:eterm_pswd])
      if rubySocket
        res = SocketHelper.getCR(rubySocket,"i",false)
        cmd = "ff:"+air_no+"/"+date
        res = SocketHelper.getCR(rubySocket,cmd,true)
        res = res.gsub(/\t/,"")
        res = res.gsub(/\n/,"<br>")
        #res = res.gsub(/ {1,}/," ")
        res = res.strip

        rubySocket.close
        rubySocket=nil

        @result = res
      else
        @result = "连接放大器失败,或用户"+session[:eterm_name].to_s+"已被占用!"
      end
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      SocketHelper.closeSocket(rubySocket)
    end
  end
  
  #使用pat:a查询票价 -- 没价格的舱位或者是特价舱才能查询
  def clickTicketTypeProcess
    begin
      
      airNo = params[:airNo]
      position = params[:position]
      fromto = params[:fromto]
      date = params[:date]
      @type = params[:grid_no]
      @type = "" if @type ==nil
      
      airNo = airNo[airNo.rindex("*")+1..-1] if airNo.rindex("*") && airNo.index("*")==0
      airways_code = airNo[0,2]
      date = CommonHelper.getCmdDateFormat(date) if date.index("-")
      
      price = 0
      rubySocket = SocketHelper.getSocket(session[:eterm_name],session[:eterm_pswd])
      if rubySocket
        res1 = SocketHelper.getCR(rubySocket,"i",false)
        #logger.error "res1="+res1
        cmd = "ss:"+airNo+position+date+fromto+"1"
        #logger.error "-----"+cmd
        res2 = SocketHelper.getCR(rubySocket,cmd,true)
        #logger.error "res2="+res2
        cmd = "pat:a"
        res3 = SocketHelper.getCR(rubySocket,cmd,true)
        #logger.error "res3="+res3
        #关闭socket链接
        if rubySocket
          rubySocket.close
          rubySocket=nil
        end
        #更新价格
        if res3.index("FARE:CNY")
          res4 = res3[res3.index("FARE:CNY")+8..-1]
          res5 = res4[0,res4.index(".")]
          price = res5.to_i
        end
        #更新航段燃油费
        if res3.index("YQ:CNY") && FuelTax.find(:first,:conditions=>["fromto=?",fromto])==nil
          res4 = res3[res3.index("YQ:CNY")+6..res3.length]
          tax = res4[0,res4.index(".")].to_i
          
          fuelTax = FuelTax.new
          fuelTax.fromto = fromto
          fuelTax.tax = tax
          fuelTax.save
          
          fuelTax = FuelTax.new
          fuelTax.fromto = fromto[3,3]+fromto[0,3]
          fuelTax.tax = tax
          fuelTax.save
        end
        res3 = res3.gsub(/\t/,"")
        res3 = res3.gsub(/\n/,"<br>")
        res3 = res3.gsub(/ {1,}/," ")
        @result = res3
        #        if price>0
        #          #如果是标准舱位，则更新价格表
        #          airways = Airways.find_by_code(airways_code)
        #          if airways
        #            standPosition = Position.find(:first,:conditions=>["position_code=? and airways_id=?",position,airways.id])
        #            if standPosition
        #              #是标准舱位
        #              today = Time.new.strftime("%Y-%m-%d")
        #              sql = "fromto='"+fromto+"' and position='"+position+"' and air_no='"+airNo+"' and special is not null and special='yes' and (start_date is null or start_date<='"+today+"') and (end_date is null or end_date>='"+today+"')"
        #              logger.error "---获取特价舱位的sql="+sql
        #              special_positionPrice = PositionPrice.find(:first,:conditions=>sql)
        #              if special_positionPrice==nil
        #                #而且不是特价舱位，则更新这个航空公司该航线上的所有不是特价的这个舱位的价格
        #                u_result = PositionPrice.update_all("price="+price.to_s,["airways_code=? and fromto=? and position=? and (special is null or special='no')",airways_code,fromto,position])
        #                logger.error "---更新结果---"
        #                logger.error u_result
        #              end
        #            end
        #          end
        #        end
      else
        @result = "连接放大器失败,或用户"+session[:eterm_name].to_s+"已被占用!"
      end
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      SocketHelper.closeSocket(rubySocket)
    end
  end
  
  #得到订单json
  def getEditOrderInfoByID
    begin
      rootStr = ""
      id = params[:id]
      order = Order.find_by_id(id)
      if order
        rootStr = order.to_json(:include=>[:customer,:creator,:ticket_outer,:printer,:cash_checker,:canceler,:sender,:jj_man,:jj_affirmer])
      end
      jsonstr="{root:["+rootStr+"]}"
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  #修改订单
  def saveEditOrder
    begin
      id = params[:id]
      order = Order.find_by_id(id) if id
      if order
        #备份
        resBK = OrderBackup.saveBK(order)
        #logger.error resBK
        
        order.last_editer_id = session[:user_id]
        if params[:onlyCustomer]
          #订单转换客户
          customer = params[:customer]
          if customer && customer.to_i>0
            order.customer_id = customer.to_i
            if !order.save
              result = "{success:false,info:'转换客户失败'}"
            else
              result = "{success:true,info:'转换客户成功'}"
            end
          end
        elsif params[:onlyJJ]
          jj_man_id = params[:jj_man_id]
          jj_address = params[:jj_address]
          jj_time = params[:jj_time]
          jj_request = params[:jj_request]
          
          order.jj_address = jj_address
          order.jj_time = jj_time
          order.jj_request = jj_request
          order.jj_man_id = jj_man_id if jj_man_id && jj_man_id.to_i>0
          if order.save
            result = "{success:true,info:'修改成功'}"
          else
            result = "{success:false,info:'修改失败'}"
          end
        else
          sender_id = params[:sender]
          link_man = params[:link_man]
          link_tel = params[:link_tel]
          send_address = params[:send_address]
          send_date = params[:send_date]
          send_time = params[:send_time]
          send_request = params[:send_request]
          order_request = params[:order_request]
          jj_address = params[:jj_address]
          jj_time = params[:jj_time]
          jj_request = params[:jj_request]
          status = params[:status]
          affirm_date = params[:affirm_date]
          
          #修改订单信息
          order.sender_id = sender_id.to_i if sender_id && sender_id.to_i>0
          order.link_man = link_man
          order.link_tel = link_tel
          order.send_address = send_address
          order.send_date = send_date
          order.send_time = send_time
          order.send_request = send_request
          order.order_request = order_request
          order.jj_address = jj_address
          order.jj_time = jj_time
          order.jj_request = jj_request
          order.affirm_date = affirm_date
          if order.save
            if status && status!=""
              Ticket.update_all(["status=?",status], :order_id => id)
            end
            result = "{success:true,info:'修改订单成功'}"
          else
            result = "{success:false,info:'修改订单失败'}"
          end
        end
      else
        result = "{success:false,info:'获取订单失败'}"
      end
      #logger.error "result="+result
      render :text=>result, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  #得到票的所有信息
  def getEditTicketInfoByID
    begin
      
      id = params[:id]
      ticket = Ticket.find_by_id(id) if id
      jsonstr = "{root:[]}"
      if ticket
        #rootStr = ticket.to_json(:include => {:passenger => {:include => :card_type}})
        rootStr = ticket.to_json(:include => [:passenger,:canceler,:insurance_outer])
        jsonstr="{root:["+rootStr+"]}"
      end
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  #保存票中费用的修改结果
  def saveEditTicket
    begin
      logger.error "========:controller=#{params[:controller]},:action=#{params[:action]}========="
      id = params[:id]
      price = params[:price]
      price_F = params[:price_F]
      fuel_tax = params[:fuel_tax]
      airdrome_tax = params[:airdrome_tax]
      insurance_number = params[:insurance_number]
      insurance_F = params[:insurance_F]
      other = params[:other]
      id_card = params[:id_card]
      point = params[:point]
      
      result = "{success:false,info:'编辑失败'}"
      ticket = Ticket.find_by_id(id) if id
      if ticket
        ticket.price = price.to_i
        ticket.price_F = price_F.to_i
        ticket.fuel_tax = fuel_tax.to_i
        ticket.airdrome_tax = airdrome_tax.to_i
        ticket.insurance_number = insurance_number.to_i
        ticket.insurance_F = insurance_F.to_i
        ticket.other = other.to_i
        ticket.point = point.to_i
        ticket.total_price = ticket.price + (Constants::DEFAULT_INSURANCE_PRICE*ticket.insurance_number) + ticket.airdrome_tax + ticket.fuel_tax + ticket.other - ticket.price_F - ticket.insurance_F
        #logger.error "ticket.total_price="+ticket.total_price.to_s
        go = true
        if id_card && id_card!="" && ticket.passenger_id
          #logger.error "乘客id="+ticket.passenger_id.to_s
          customer = ticket.passenger
          #customer = Customer.find_by_id(ticket.passenger_id)
          #logger.error "乘客="+customer.name
          #logger.error "乘客旧证件号="+customer.card
          #logger.error "新证件号id_card="+id_card
          
          #如果身份证号发生改变,需要提取pnr然后修改其中的证件号码信息
          if customer && customer.card!=id_card
            #修改pnr记录
            res = CommonHelper.changeCardIdByPnr(ticket.pnr,customer.name,customer.card,id_card,session[:eterm_name],session[:eterm_pswd])
            if res.index("成功")==nil
              go = false
              result = "{success:true,info:'修改PNR中证件号记录失败,返回信息:"+res+"'}"
            else
              customer.card=id_card
              if !customer.save
                go = false
                result = "{success:true,info:'保存常旅客证件号失败'}"
              end
            end
          end
        end
        if go
          if ticket.save
            order = ticket.order
            sql = "select sum(total_price) as sum from tickets where order_id="+order.id.to_s
            sql << " and status not in('"+Constants::TICKET_STATUS_YQX+"','"+Constants::TICKET_STATUS_YTP+"','"+Constants::TICKET_STATUS_YZF+"')"
            order_sums = Order.find_by_sql(sql)[0]
            price_sum = order_sums.sum.to_i
            #logger.error "price_sum="+price_sum.to_s
            order.price_sum = price_sum
            if order.save
              result = "{success:true,info:'编辑成功'}"
            else
              result = "{success:true,info:'记录已保存,但维护订单总价格失败'}"
            end
          else
            result = "{success:true,info:'保存记录失败'}"
          end
        end
      else
        result = "{success:true,info:'获取记录失败'}"
      end
      render :text=>result, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  #退票
  def saveDrawTicket
    begin
      id = params[:tid]
      money = params[:d_money]
      remark = params[:d_remark]
      
      result = "{success:false,info:'退票失败'}"
      ticket = Ticket.find_by_id(id) if id
      if ticket
        #pnr = ticket.pnr
        #logger.error "pnr="+pnr
        #pass_name = ticket.passenger.name
        #TODO 退票命令在eterm中完成
        #res = CommonHelper.getCancelTicketResult(pnr,pass_name,session[:eterm_name],session[:eterm_pswd])
        #logger.error "-----取消乘客"+pass_name+"结果res="+res
        #if res.index("成功") || res.index("已经被取消")
        if CommonHelper.saveDrawTicket(session[:user_id],id,money,remark)
          result = "{success:true,info:'退票成功'}"
        else
          result = "{success:true,info:'退票失败'}"
          #result = "{success:false,info:'乘客"+pass_name+"信息已经取消,但是保存退票信息失败'}"
        end
        #else
        #  result = "{success:false,info:'取消乘客"+pass_name+"信息失败,返回结果:#{res}'}"
        #end
      end
      #logger.error result
      render :text=>result, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  def getJJList
    begin
      jj_status = params[:jj_status]
      date = params[:date]
      date_to = params[:date_to]
      pnr = params[:pnr]
      no = params[:no]
      
      sql = " status not in('"+Constants::ORDER_STATUS_YQX+"','"+Constants::ORDER_STATUS_YTD+"','"+Constants::ORDER_STATUS_YZF+"')"
      sql << " and jj_address is not null and jj_time is not null and jj_time<>''"
      today = Time.new.strftime("%Y-%m-%d")
      if date && date!=""
        sql << " and fly_date>='"+date+"'"
      else
        sql << " and fly_date>='"+today+"'"
      end
      if date_to && date_to!=""
        date_to = (date_to.to_date+1).to_s
        sql << " and fly_date<'"+date_to+"'"
      else
        date_to = (today.to_date+1).to_s
        sql << " and fly_date<'"+date_to+"'"
      end
      if pnr && pnr!=""
        sql << " and pnr='"+pnr+"'"
      end
      if no && no!=""
        sql << " and order_no='"+no+"'"
      end
      if jj_status && jj_status=="已确认"
        sql << " and jj_request<>'已取消' and jj_affirm_id is not null and jj_affirm_id<>1"
      elsif jj_status && jj_status=="未确认"
        sql << " and jj_request<>'已取消' and (jj_affirm_id is null or jj_affirm_id=0 or jj_affirm_id=1)"
      elsif jj_status && jj_status=="已取消"
        #如果接机取消 则接机要求变为已取消
        sql << " and jj_request='已取消'"
      end
      sql << " AND is_locked <> 1"
      logger.error "sql="+sql
      
      pageBegin = params[:start]
      pageEnd = params[:limit]
      logger.error pageBegin
      logger.error pageEnd
      
      num = 0
      rootStr = "[]"
      pageOrders = Order.find(:all,:conditions => sql)
      num = pageOrders.length if pageOrders
      orders = Order.find(:all,:conditions => sql,:limit =>pageBegin+","+pageEnd)
      if orders && orders.length>0
        rootStr = orders.to_json(:include=>[:customer,:creator,:ticket_outer,:printer,:cash_checker,:canceler,:sender,:jj_man,:jj_affirmer])
      end
      jsonstr="{totalProperty:"+num.to_s+",root:"+rootStr+"}"
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  def cancelJJ
    begin
      id = params[:id]
      order = Order.find_by_id(id) if id
      if order
        order.jj_request = "已取消"
        if order.save
          result = "取消成功"
        else
          result = "取消失败"
        end
      else
        result = "获取订单信息失败"
      end
      render :text=>result, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  def affirmJJ
    begin
      id = params[:id]
      jj_man = params[:jj_man]
      order = Order.find_by_id(id)
      if order
        order.jj_man_id = jj_man.to_i if jj_man && jj_man.to_i>0
        order.jj_affirm_id = session[:user_id]
        order.jj_affirm_date = Time.new
        if order.save
          result = "{success:true,info:'确认接机成功'}"
        else
          result = "{success:false,info:'保存确认信息失败'}"
        end
      else
        result = "{success:false,info:'获取订单记录失败 id=#{id}'}"
      end
      render :text=>result, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  #参加活动
  def saveActivity
    begin
      id = params[:id]
      activity = params[:activity_type]
      order = Order.find_by_id(id) if id
      if order
        order.activity = activity
        if order.save
          #TODO 参加活动就不积分 不返现？如果是后参加活动 是否需要扣除积分？
          #Ticket.update_all("point=0,price_F=0",["order_id=? and is_locked<>1",id])
          Ticket.update_all("point=0",["order_id=? and is_locked<>1",id])
          
          result = "{success:true,info:'保存活动成功'}"
        else
          result = "{success:false,info:'保存活动失败'}"
        end
      else
        result = "{success:false,info:'获取订单记录失败'}"
      end
      render :text=>result, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  #查看订单修改记录
  def getOrderUpdateHis
    begin
      from_date = params[:from_date]
      to_date = params[:to_date]
      pageBegin = params[:start]
      pageEnd = params[:limit]
      num = 0
      rootStr = "[]"
      sql = "order_id is not null"
      if from_date && to_date
        to_date = (to_date.to_date+1).to_s
        sql << " and created_at>='"+from_date+"' and created_at<='"+to_date+"'"
      end
      sql << " AND is_locked <> 1"
      #logger.error sql
      pages = OrderBackup.find(:all,:conditions=>sql)
      num = pages.length if pages 
      backups = OrderBackup.find(:all,:conditions=>sql,:group=>'order_id',:order=>'created_at',:limit=>pageBegin+","+pageEnd)
      if backups
        rootStr = backups.to_json(:include=>[:customer,:creator,:ticket_outer,:printer,:cash_checker,:sender,:canceler,:jj_man,:jj_affirmer])
      end
      jsonstr="{totalProperty:"+num.to_s+",root:"+rootStr+"}"
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  def getPnrInfo
    begin
      id = params[:id]
      order = Order.find_by_id(id)
      if order
        pnr = order.pnr
        cmd = "rt"+pnr
        res = SocketHelper.callSocket(cmd,session[:eterm_name],session[:eterm_pswd])
        #logger.error res
        if res.index("失败")
          res = res
        elsif res.index("timeout")
          res = "连接服务器超时!"
        elsif res.index("socket is null") || res==""
          res = "访问服务器失败!"
        elsif res.index(pnr)
          res = res.gsub(/\r/,"<br>")
          res = res.gsub(/\n/,"<br>")
          res = res.gsub(/ {2,}/," ")
          res = res.strip
          if res.index("*THIS PNR WAS ENTIRELY CANCELLED*")==nil
            res2 = res
            while(res2.index(". "))
              res3 = res2[res2.index(". ")+2..-1]
              res4 = res3[0,res3.index("<br>")].strip
              #logger.error  "-----行结果="+res4
              air_no = res4[0,res4.index(" ")]
              air_no = air_no[1..-1] if air_no.index("*")
              res4 = res4[res4.index(" ")+1..-1]
              position = res4[0,res4.index(" ")]
              res4 = res4[res4.index(" ")+1..-1]
              #res5 = res4[0,res4.index(" ")]
              res4 = res4[res4.index(" ")+1..-1]
              #fromto = res4[0,res4.index(" ")]
              res4 = res4[res4.index(" ")+1..-1]
              res5 = res4[0,res4.index(" ")]
              status_type = res5[0,2]
              #logger.error status_type
              #更新舱位状态
              Ticket.update_all("status_type='"+status_type+"'",["order_id=? and air_no=? and position=?",id,air_no,position])
              
              res2 = res3[res3.index("<br>")+4..-1].strip
            end
          end
        end
        @res = res
      else
        @res = "获取PNR失败"
      end
      logger.error @res
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  #追加婴儿票
  def addChildTicket
    begin
      id = params[:id]
      name = params[:baby_name]
      date = params[:baby_date]
      insurance_number = params[:insurance_number]
      
      logger.error id
      logger.error name
      logger.error date
      logger.error insurance_number
      
      baby_date = CommonHelper.getCmdDateFormat(date) if date
      
      result = "{success:false}"
      ticket = Ticket.find_by_id(id)
      if ticket
        #判断是否已经有婴儿票
        if Ticket.find(:first,:conditions=>[" father_id is not null and father_id=?",ticket.id])
          result = "{success:false,info:'该乘客已经有一位婴儿,每位乘客只能带一个婴儿'}"
        else
          if ticket.passenger
            p_name = ticket.passenger.name
            pnr = ticket.pnr
            airNo = ticket.air_no
            fromto = ticket.fromto
            position = ticket.position
            fly_date = CommonHelper.getCmdDateFormat(ticket.fly_date.to_s)
            
            rubySocket = SocketHelper.getSocket(session[:eterm_name],session[:eterm_pswd])
            if rubySocket
              res = SocketHelper.getCR(rubySocket,"i",false)
              cmd = "rt"+pnr
              logger.error "-----命令cmd="+cmd
              res = SocketHelper.getCR(rubySocket,cmd,true)
              logger.error "-----返回结果res="+res
              if res.index("timeout")
                result = "{success:false,info:'连接服务器超时!'}"
              elsif res.index("socket is null") || res==""
                result = "{success:false,info:'访问服务器失败!'}"
              elsif res.index("NO PNR")
                result = "{success:false,info:'该PNR不存在!'}"
              elsif res.index("*THIS PNR WAS ENTIRELY CANCELLED*")
                result = "{success:false,info:'该PNR已经被取消!'}"
              else
                res = res.gsub(/\r/,"")
                res = res.gsub(/\n/,"<br>")
                res1 = res.gsub(/ {1,}/," ")
                logger.error "-----整理后结果res1="+res1
                
                if res1.index("."+p_name)
                  no = res1[res1.index("."+p_name)-1,1]
                  logger.error "no="+no
                  if no.to_i>0
                    #TODO 如果该大人已经有一个婴儿,穿入命令中怎么设置P后面的数字? /P2
                    baby_name = SocketHelper.getTransChineseName(name)
                    logger.error "baby_name="+baby_name
                    cmd = "XN:IN/"+baby_name+"INF("+baby_date[2,5]+")/P"+no
                    logger.error "-----命令cmd="+cmd
                    res2 = SocketHelper.getCR(rubySocket,cmd,true)
                    logger.error "-----返回结果res2="+res2
                    if res2.index("XN/IN")
                      if name.index("/")
                        name_pinyin = name
                      else
                        xing = SocketHelper.getPinYin(name[0,3])
                        ming = SocketHelper.getPinYin(name[3..-1])
                        logger.error "姓="+xing
                        logger.error "名="+ming
                        name_pinyin = xing+"/"+ming
                      end
                      cmd = "SSR INFT "+airNo[0,2]+" NN1 "+fromto+" "+airNo[2..airNo.length]+" "+position+fly_date+" "+name_pinyin+" "+baby_date+"/P"+no
                      logger.error "-----命令cmd="+cmd
                      res3 = SocketHelper.getCR(rubySocket,cmd,true)
                      logger.error "-----返回结果res3="+res3
                      if res3.index("SSR INFT ")
                        res4 = SocketHelper.getCR(rubySocket,"@",true)
                        logger.error "-----封口结果res4="+res4
                        if res4.index(airNo) && res4.index(pnr)
                          result = "{success:true,info:'订票成功'}"
                          saveBB = CommonHelper.saveBabyTicket(id,name,date,insurance_number)
                          if saveBB==nil
                            result = "{success:false,info:'PNR已经生成,但是保存信息失败,请务必妥善保存PNR:<font color=red>#{pnr}</font>,可利用导入功能将该pnr信息导入系统'}"
                          else
                            logger.error "-----保存婴儿票数据库结果 id="+saveBB.to_s
                          end
                        end
                      else
                        result = "{success:false,info:'穿入命令"+cmd+"失败'}"
                      end
                    else
                      result = "{success:false,info:'穿入命令"+cmd+"失败'}"
                    end
                  else
                    result = "{success:false,info:'获取乘客"+p_name+"在PNR信息中的编号失败'}"
                  end
                else
                  result = "{success:false,info:'PNR信息中没有乘客"+p_name+"'}"
                end
              end
              if rubySocket
                rubySocket.close
                rubySocket=nil
              end
            else
              result = "{success:false,info:'连接放大器失败,或用户"+session[:eterm_name].to_s+"已被占用!'}"
            end
          else
            result = "{success:false,info:'获得大人乘客的姓名失败'}"
          end
        end
      else
        result = "{success:false,info:'参数传递错误'}"
      end
      logger.error "result="+result
      render :text=>result, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
      SocketHelper.closeSocket(rubySocket)
    end
  end
  
  def hotelBooking
    begin
      @customer_id = "1"
      phone = params[:phone_number]
      customer = Customer.find(:first,:conditions=>["phone=?",phone])
      if customer
        @customer_id = customer.id.to_s
      end
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  def getHotelOrders
    begin
      
      strdelData = params[:delData]
      if strdelData!=nil
        delHotelOrder(strdelData)
        logger.error "------------delHotelOrder End Delete-----------------"
      end
      dateBegin = params[:date_begin]
      dateEnd = params[:date_end]
      status = params[:status]
      myHotelOrder = params[:my_hotel_order]
      if dateBegin !="" && dateBegin !=nil
        if status !=nil && status !=""
          if myHotelOrder=="true"
            hotelOrders = HotelOrder.find(:all,:conditions=>["user_id = ? AND status = ? AND created_at >= ? AND created_at <= ? AND is_locked <> 1",session[:user_id],status,dateBegin,dateEnd])
          else
            hotelOrders = HotelOrder.find(:all,:conditions=>["status = ? AND created_at >= ? AND created_at <= ? AND is_locked <> 1",status,dateBegin,dateEnd])
          end
        else
          if myHotelOrder=="true"
            hotelOrders = HotelOrder.find(:all,:conditions=>["user_id = ? AND created_at >= ? AND created_at <= ? AND is_locked <> 1",session[:user_id],dateBegin,dateEnd])
          else
            hotelOrders = HotelOrder.find(:all,:conditions=>["created_at >= ? AND created_at <= ? AND is_locked <> 1",dateBegin,dateEnd])
          end
        end
      else
        if myHotelOrder=="true"
          hotelOrders = HotelOrder.find(:all,:conditions=>["user_id = ? AND is_locked <> 1",session[:user_id]])
        else
          hotelOrders = HotelOrder.find(:all,:conditions=>["is_locked <> 1"])
        end
      end
      
      jsonstr="{root:"+hotelOrders.to_json(:include=>[:customer,:user])+"}"
      
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  def delHotelOrder(strdelData)
    ids=""
    begin
      
      results = ActiveSupport::JSON.decode(strdelData)
      results.each do |result|
        ids << result["id"]+","
      end
      ids = ids[0,ids.length-1]
      #对于普通用户只是加锁,不是删除.
      logger.error ids
      HotelOrder.update_all("is_locked = 1",["id in ("+ids+") AND user_id = ?",session[:user_id]])
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  def addHotelOrder
    begin
      
      hotelOrder = HotelOrder.new()
      hotelOrder.user_id = session[:user_id]
      hotelOrder.roomer_name = params[:roomer_name]
      hotelOrder.roomer_phone = params[:roomer_phone]
      hotelOrder.room_type = params[:room_type]
      hotelOrder.room_price = params[:room_price]
      hotelOrder.cost_price = params[:cost_price]
      hotelOrder.room_number = params[:room_number]
      hotelOrder.people_number = params[:people_number]
      hotelOrder.day_number = params[:day_number]
      hotelOrder.date_begin = params[:date_begin]
      hotelOrder.date_end = params[:date_end]
      hotelOrder.time_begin = params[:time_begin]
      hotelOrder.time_end = params[:time_end]
      hotelOrder.pay_type = params[:pay_type]
      hotelOrder.status = params[:status]
      hotelOrder.remark = params[:remark]
      customer_id = params[:customer_id]
      if customer_id == ""
        hotelOrder.customer_id = 1
      else
        hotelOrder.customer_id = customer_id
      end
      
      logger.error "customer_id----------------"
      logger.error params[:customer_id]
      hotelOrder.save
      info = "添加酒店订单成功"
      jsonstr="{success:true,info:'#{info}'}"
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  def getHotelOrderByID
    begin
      
      hotelOrder = HotelOrder.find(:first,:conditions=>["id = ?",params[:id]])
      jsonstr="{root:["+hotelOrder.to_json()+"]}"
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  def editHotelOrder
    begin
      hotelOrder = HotelOrder.find(:first,:conditions=>["id = ?",params[:id]])
      hotelOrder.user_id = session[:user_id]
      hotelOrder.roomer_name = params[:roomer_name]
      hotelOrder.roomer_phone = params[:roomer_phone]
      hotelOrder.room_type = params[:room_type]
      hotelOrder.room_price = params[:room_price]
      hotelOrder.cost_price = params[:cost_price]
      hotelOrder.room_number = params[:room_number]
      hotelOrder.people_number = params[:people_number]
      hotelOrder.day_number = params[:day_number]
      hotelOrder.date_begin = params[:date_begin]
      hotelOrder.date_end = params[:date_end]
      hotelOrder.time_begin = params[:time_begin]
      hotelOrder.time_end = params[:time_end]
      hotelOrder.pay_type = params[:pay_type]
      hotelOrder.status = params[:status]
      hotelOrder.remark = params[:remark]
      hotelOrder.save
      info = "编辑酒店订单成功"
      jsonstr="{success:true,info:'#{info}'}"
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  #VIP统计
  def expenditureList
    #权限
    if CommonHelper.rightAuthorization(session[:user_rights],params[:controller],params[:action]) == "false"
      redirect_to(:controller => "index", :action => "main") and return
    end
  end
  
  #客户消费统计
  def getExpenditureList
    begin
      logger.error "===== orders getExpenditureList ====="
      from_date = params[:from_date]
      to_date = params[:to_date]
      
      rootStr = ""
      date_sql = ""
      if from_date && to_date
        to_date = (to_date.to_date+1).to_s
        date_sql = " created_at>'"+from_date+"' and created_at<'"+to_date+"' "
      end
      status_sql = " status<>'"+Constants::ORDER_STATUS_YQX+"' and status<>'"+Constants::ORDER_STATUS_YZF+"' "
      sql = "select DISTINCT customer_id from orders where "+status_sql+" and "+date_sql+" order by customer_id"
      logger.error sql
      customers = Customer.find(:all,:conditions=>"id<>1 and id in("+sql+")",:order=>"id")
      for customer in customers
        order_sum = 0
        price_sum = 0
        expenditure_sum = 0
        tax_sum = 0
        fuel_sum = 0
        f_sum = 0
        point_sum = 0
        
        rootStr << "," if rootStr!=""
        id = customer.id.to_s
        sql = "select count(*) as order_sum,sum(price_sum) as e_sum from orders where customer_id="+id+" and "+status_sql+" and "+date_sql
        logger.error sql
        order = Order.find_by_sql(sql)[0]
        if order
          logger.error "订单数="+order.order_sum.to_s
          logger.error "消费数="+order.e_sum.to_s
          
          order_sum = order.order_sum
          expenditure_sum = order.e_sum
        end
        t_status_sql = " status<>'"+Constants::TICKET_STATUS_YQX+"' and status<>'"+Constants::TICKET_STATUS_YTP+"' "
        logger.error sql
        sql = "select sum(price) as price_sum,sum(price_F) as f_sum,sum(point) as point_sum,sum(airdrome_tax) as tax_sum,sum(fuel_tax) as fuel_sum from tickets where customer_id="+id+" and "+t_status_sql+" and "+date_sql
        order = Order.find_by_sql(sql)[0]
        if order
          logger.error "票面价="+order.price_sum.to_s
          logger.error "返现="+order.f_sum.to_s
          logger.error "积分="+order.point_sum.to_s
          logger.error "税费="+order.tax_sum.to_s
          logger.error "附加="+order.fuel_sum.to_s
          
          price_sum = order.price_sum
          f_sum = order.f_sum
          point_sum = order.point_sum
          tax_sum = order.tax_sum
          fuel_sum = order.fuel_sum
        end
        
        linkman = ""
        linkman_phone = ""
        customer_no = ""
        customer_type = ""
        customer_level = ""
        linkman = customer.linkman if customer.linkman
        linkman_phone = customer.linkman_phone if customer.linkman_phone
        customer_no = customer.customer_no if customer.customer_no
        customer_type = customer.customer_type.customer_type if customer.customer_type
        customer_level = customer.customer_level if customer.customer_level
        
        rootStr << "{'id':'"+id+"','name':'"+customer.name+"','customer_no':'"+customer_no+"','customer_type':'"+customer_type+"','customer_level':'"+customer_level+"','linkman':'"+linkman+"','linkman_phone':'"+linkman_phone+"','order_sum':'"+order_sum.to_s+"','price_sum':'"+price_sum.to_s+"','tax_sum':'"+tax_sum.to_s+"','fuel_sum':'"+fuel_sum.to_s+"','point_sum':'"+point_sum.to_s+"','f_sum':'"+f_sum.to_s+"','expenditure_sum':'"+expenditure_sum.to_s+"'}"
      end
      
      logger.error rootStr
      jsonstr="{root:["+rootStr+"]}"
      
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  def getPassengerNamesById
    begin
      id = params[:id]
      #logger.error id
      rootStr = ""
      sql = "select distinct passenger_id from tickets where order_id="+id+" and is_locked<>1"
      sql << " and status <> '"+Constants::TICKET_STATUS_YQX+"' and status <> '"+Constants::TICKET_STATUS_YTP+"' and status <> '"+Constants::TICKET_STATUS_YZF+"'"
      #logger.error sql
      tickets = Ticket.find_by_sql(sql)
      for ticket in tickets
        pass_id = ticket.passenger_id
        customer = Customer.find_by_id(pass_id) if pass_id
        if customer
          rootStr << "," if rootStr!=""
          rootStr << "{'id':'"+pass_id.to_s+"','pass_name':'"+customer.name+"'}"
        end
      end
      #logger.error rootStr
      jsonstr="{root:["+rootStr+"]}"
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  #分离PNR
  def saPnr
    begin
      id = params[:id]
      nameStr = params[:name_str]
      idStr = params[:id_str]
      logger.error idStr
      logger.error nameStr
      user = User.find_by_id(session[:user_id])
      order = Order.find_by_id(id) if id
      info = "失败"
      if order && user
        pnr = order.pnr.upcase
        rubySocket = SocketHelper.getSocket(session[:eterm_name],session[:eterm_pswd])
        if rubySocket
          cmd = "rt"+pnr
          logger.error  "-----提取命令="+cmd
          res = SocketHelper.getCR(rubySocket,cmd,true)
          logger.error  "-----提取结果="+res
          if res.index("NO PNR")
            info = "NO PNR"
          elsif res.index("*THIS PNR WAS ENTIRELY CANCELLED*")
            info = "该PNR已经被取消"
          elsif res.index(pnr)
            res = res.gsub(/\r/,"")
            res = res.gsub(/\n/,"<br>")
            res = res.gsub(/ {2,}/," ")
            res = res.strip

            air_no = nil
            air_no2 = nil
            air_no3 = nil
            air_no4 = nil
            #            res1 = res
            #            while res1.index(". ")
            #              res2 = res1[res1.index(". ")+2..-1].strip
            #              if air_no==nil
            #                air_no = res2[0,res2.index(" ")]
            #              elsif air_no2==nil
            #                air_no2 = res2[0,res2.index(" ")]
            #              elsif air_no3==nil
            #                air_no3 = res2[0,res2.index(" ")]
            #              elsif air_no4==nil
            #                air_no4 = res2[0,res2.index(" ")]
            #              end
            #              res1 = res2[res2.index("<br>")+4..-1]
            #            end
            #            logger.error "-----air_no-----"
            #            logger.error air_no
            #            logger.error air_no2
            #            logger.error air_no3
            #            logger.error air_no4
            
            noStr = ""
            idArr = idStr.split(",")
            for pid in idArr
              logger.error pid
              customer = Customer.find_by_id(pid)
              pass_name = customer.name
              logger.error pass_name
              if res.index("."+pass_name)
                no = res[res.index("."+pass_name)-1,1]
                logger.error no
                noStr << "/" if noStr!=""
                noStr << no
              end
            end
            logger.error "-----noStr="+noStr
            cmd = "SP"+noStr
            logger.error  "-----分离命令="+cmd
            restr = SocketHelper.getCR(rubySocket,cmd,true)
            logger.error  "-----分离结果="+restr
            restr = SocketHelper.getCR(rubySocket,"@",true)
            logger.error  "-----封口结果="+restr
            restr = restr.gsub(/\r/,"")
            restr = restr.gsub(/\n/,"<br>")
            restr = restr.gsub(/ {2,}/," ")
            restr = restr.strip

            #restr = CommonHelper.getPnrFromSocketResult(restr,air_no,air_no2,air_no3,air_no4)
            if restr.index(" SPLIT FROM") && restr.index(" SPLIT FROM")==5
              new_pnr = restr[0,5]
              #status_type = restr[6,2]
            else
              new_pnr = ""
              #status_type = ""
            end
            logger.error "----获取PNR="+new_pnr+"----"
            if new_pnr.length==5
              #得到分离出票的总价格
              sql = "select sum(total_price) as total from tickets where order_id="+id+" and passenger_id in ("+idStr+") and is_locked<>1"
              logger.error sql
              tickets = Ticket.find_by_sql(sql)
              total = tickets[0].total
              logger.error total

              #复制原记录，保存乘客信息
              new_order = Order.new
              order.attributes.each do |attr, value|
                eval("new_order.#{attr} = order.#{attr}") if attr!="id" && attr!="pnr" && attr!="order_no"
              end
              new_order.order_no = CommonHelper.getNewOrderNo(user.employee_no)
              new_order.pnr = new_pnr
              new_order.id = nil
              new_order.price_sum = total.to_i
              new_order.seat = idArr.length
              if new_order.save
                #更新旧订单总金额
                order.price_sum -= total.to_i
                order.save
                #更新票记录中的数据
                new_orderid = new_order.id
                logger.error "-----新订单数据库id"
                logger.error new_orderid
                num = Ticket.update_all("pnr='"+pnr+"',order_id="+new_orderid.to_s,["order_id=? and passenger_id in(?) and is_locked<>1",id,idStr])
                logger.error num
                info = "分离成功"
              else
                info = "分离出PNR是#{new_order},保存新订单记录失败"
              end
            else
              info = "分离PNR失败,分离结果:"+restr
            end
          else
            info = "提取PNR失败,返回信息:"+res
          end
          if rubySocket
            rubySocket.close
            rubySocket=nil
          end
        else
          info = "连接放大器失败,或用户已被占用!"
        end
      else
        info = "获取参数失败"
      end
      logger.error info
      result = "{success:true,info:'#{info}'}"
      render :text=>result, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  #查看Q结果
  def clearQ
    #权限
    if CommonHelper.rightAuthorization(session[:user_rights],params[:controller],params[:action]) == "false"
      redirect_to(:controller => "index", :action => "main") and return
    end 
    begin
      #logger.error "=======session[:user_id]:"+session[:user_id].to_s+" clearQ ================"
      rubySocket = SocketHelper.getSocket(session[:eterm_name],session[:eterm_pswd])
      if rubySocket
        cmd = "QT"
        res = SocketHelper.getCR(rubySocket,cmd,false)
        #logger.error "----QT结果----"
        #logger.error res
        res = res.gsub(/\r/,"")
        #logger.error res.index("\n")
        #logger.error res.rindex("\n")
        res = res[res.index("\n")..res.rindex("\n")-3]
        res = res.gsub(/\n/,"\\n")
        #res = res.gsub(/ {2,}/," ")
        if rubySocket
          rubySocket.close
          rubySocket=nil
        end
      else
        res = "连接放大器失败,或用户"+session[:eterm_name]+"已被占用!"
      end
      #logger.error res
      @res = res
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  #查看Q内容
  def getQ
    begin
      part = params[:part]
      rootStr = ""
      rubySocket = SocketHelper.getSocket(session[:eterm_name],session[:eterm_pswd])
      if rubySocket
        rootStr << "["
        cmd = "QS "+part
        #logger.error "----查询命令="+cmd
        res = SocketHelper.getCR(rubySocket,cmd,true)
        #logger.error "----QS结果----"
        #logger.error res
        res = res.gsub(/\r/,"")
        res = res.gsub(/\n/,"<br>")
        res = res.gsub(/ {2,}/," ")
        res = res[0,res.rindex("<br>")] if res.rindex("<br>")
        res = res[0,res.rindex("<br>")] if res.rindex("<br>")
        #logger.error  "-----整理后结果res="+res
        rootStr << "{'info':'"+res+"'}"
        if res.index("EMPTY")==nil && res.index("WORKING")==nil
          #既不是空也不是正在处理 就继续翻页
          while res.rindex("(") && res.rindex(")") && res.rindex("(")<res.rindex(")") && res[res.rindex("(")+1..res.rindex(")")-1].to_i>0
            #logger.error "------------"+res[res.rindex("(")+1..res.rindex(")")-1]+"--------------"
            cmd = "QD"
            res = SocketHelper.getCR(rubySocket,cmd,true)
            #logger.error "----QD结果----"
            #logger.error res
            res = res.gsub(/\r/,"")
            res = res.gsub(/\n/,"<br>")
            res = res.gsub(/ {2,}/," ")
            res = res[0,res.rindex("<br>")] if res.rindex("<br>")
            res = res[0,res.rindex("<br>")] if res.rindex("<br>")
            rootStr << ",{'info':'"+res+"'}"
          end
          cmd = "QDE"
          res = SocketHelper.getCR(rubySocket,cmd,true)
          #logger.error "----QDE结果="+res
        end
        rootStr << "]"
        if rubySocket
          rubySocket.close
          rubySocket=nil
        end
      else
        res = "连接放大器失败,或用户"+session[:eterm_name]+"已被占用!"
        rootStr = "[{'info':'"+res+"'}]"
      end
      #logger.error rootStr
      jsonstr="{root:"+rootStr+"}"
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  #根据pnr保存成订单
  def getOrderInfoByPnr
    begin
      orderid = ""
      rootStr = ""
      pnr = params[:pnr]
      type = params[:type]
      if pnr && pnr.length==5
        pnr = pnr.upcase
        #查询30天之内有没有重复的pnr
        today = Time.new.strftime("%Y-%m-%d")
        limit_date = (today.to_date-Constants::PNR_REPEAT_DAY).to_s
        order = Order.find(:first,:conditions=>["pnr=? and created_at>?",pnr,limit_date])
        if order
          orderid = order.id
          info = "系统中已经存在#{pnr}的订单记录"
          rootStr = order.to_json(:include=>[:customer,:creator,:ticket_outer,:printer,:cash_checker,:canceler,:sender,:jj_man,:jj_affirmer])
        else
          info = CommonHelper.saveOrderByPnr(pnr,type,session[:user_id],session[:eterm_name],session[:eterm_pswd])
          if info.to_i>0
            #返回的是数字,则表示提取保存成功
            orderid = info.to_i
            order = Order.find_by_id(orderid)
            info = "提取成功"
            rootStr = order.to_json(:include=>[:customer,:creator,:ticket_outer,:printer,:cash_checker,:canceler,:sender,:jj_man,:jj_affirmer])
          end
        end
      else
        info = "输入的PNR有误,必须是5为字母或数字组成!"
      end
      jsonstr="{root:["+rootStr+"],info:'"+info+"',orderid:'"+orderid.to_s+"'}"
      render :text=>jsonstr, :layout=>false
    rescue Exception => e
      CommonHelper.infoLogger(session[:user_id],request.env["REMOTE_ADDR"],params[:controller],params[:action],e,"error")
    end
  end
  
  def printInsuranceWindow
    puts "printInsuranceWindow"
  end
end
